|
|
|
|
|
by Too
3977 days ago
|
|
I've had very nasty experiences with bitfields even though the order was well defined on that platform. It was an embedded system where someone got the idea to create bitfield access to a cpu register. The problem was that some bits in that register would be cleared automatically each time, so even if you wrote 0 it would read back as 1 the next time. Some other bit would always trigger an action if you wrote to it regardless if you wrote the same value as it had before, this was called the send_bit and when you wrote 0 it sent some stuff onto the network cable. So code that looked perfectly fine like this: register.bitsa = 0x2;
register.bitsb = 0x1;
register.send_bit = 0.
Actually sent 3 packets instead of 1 because the compiler translated each write of a bitfield member to a write of the whole register, some other bits in bitsa could get corrupted by the bitsb-write since they didn't read back as they were written. I assume the cpu had a minimum addressable unit of 8 bits so the compiler had to translate each line into something like register = (register | setbits) & clearbits; which requires reading the previous value each time just to write a single bit, this is very easy to overlook when you just see the three lines of code being written in a neat sequence. |
|
So the problem was the fact that the language gives the impression of having more control than what the hardware is actually offering. In this case bit access must have been better left to platform-dependent libraries (when it would present itself as something more than what masks usage can do).