4

From this question I learned that anonymous structs and unions had been part of the C11 standard (from the comments). Then I thought it might be a good idea to use bitfield union to replace bitmask, and I found someone else had already posted a question and shown an example, which is exactly the same as my idea. And the answers to that question agreed on the safety of using bitfield union method to replace bitmask. However, the answers to the post there, as I understood, denied the safety of accessing inactive union member, saying that accessing inactive union member is undefined behavior. I think the answers to these two questions are contradictory:

Just using the example there, after modifying .user, the value of .raw will become undefined (by answers to the post). So I think it is not safe to use bitfield union method to replace bitmask.

Am I right? or I misunderstood these answers?

Edit: If the answer to my question is different for C and C++, I wish to know both of them.

Community
  • 1
  • 1
ACcreator
  • 1,362
  • 1
  • 12
  • 29

1 Answers1

3

You're correct: there might be cases in which union bitfields might suffice to your goals but as a general approach it is not portable and safe because of how machine words are stored or accessed in memory.

C11 allows you to reinterpret the data as you want while C++11 explicitly disallows that (9.5.1). You can't expect though to have portable code if you expect machine-words bits to be arranged in a particular order everywhere.

If you read/write to them in a bytewise-fashion there will be no problems but as long as portability and safety on other platforms is at stake you can't really expect to find the same internal bit format when storing an integer on a big-endian machine or a little-endian one.

Marco A.
  • 43,032
  • 26
  • 132
  • 246