🔥 𝗖 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 – 𝗕𝗶𝘁-𝗳𝗶𝗲𝗹𝗱 𝗔𝗱𝗱𝗿𝗲𝘀𝘀𝗶𝗻𝗴 Let’s test your understanding of 𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀 𝗮𝗻𝗱 𝗯𝗶𝘁-𝗳𝗶𝗲𝗹𝗱𝘀 𝗶𝗻 𝗖. Consider the following code. ❓ 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗳𝗼𝗿 𝗖 / 𝗘𝗺𝗯𝗲𝗱𝗱𝗲𝗱 𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝘀 What will happen when this program is compiled? A️) Both addresses will print normally B️) Compiler error for ptr2 C️) Runtime crash D️) Undefined behavior but compiles successfully 💡 𝗕𝗼𝗻𝘂𝘀 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: Why does the C standard treat 𝗯𝗶𝘁-𝗳𝗶𝗲𝗹𝗱𝘀 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁𝗹𝘆 𝗳𝗿𝗼𝗺 𝗻𝗼𝗿𝗺𝗮𝗹 𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗺𝗲𝗺𝗯𝗲𝗿𝘀 𝘄𝗵𝗲𝗻 𝗶𝘁 𝗰𝗼𝗺𝗲𝘀 𝘁𝗼 𝗮𝗱𝗱𝗿𝗲𝘀𝘀𝗶𝗻𝗴? 💬 Drop your answer in the comments and explain 𝘄𝗵𝘆. Let's see how many developers know this subtle C language rule! #CProgramming #EmbeddedSystems #BitFields #InterviewQuestion #CodingChallenge #SoftwareEngineering
My question about such code examples remains the same. Why would anyone want to write code like this, that is why would anyone need to create another pointer to a bitfield? Isn't the standard way of access good enough? Trick questions should enlighten about plausible code.
Have done C for years. The answer is simple. "I don't have a clue". The one thing I do know though is that if I saw that code when doing a review, I'd say "Change it to something sensible"
Just a hint on syntax. A pointer is the type, so a typical coding standard syntax is int* (int* ptr), noting the spacing. No project I've seen in the last decade uses basic C types like int, it's always int16_t, uint16_t, int32_t, uint32_t so that it's explicit what the exact use is. Like the other comments, who writes code like this? #codingstandard #MISRA #anysecuresystem
cant take addr of bit field its a storage rule only hence compile error. In case of ptr - treats a mem cells as int storage not unsigned int - a compiler warning or error if -Werror. First printf - undefined behavior if sys address width doesnt fit to unsigned int if less will read a garbage from the stack be filled as upper bits. The second printf irrelevant since cant take address of thumb operations operands (bit banging or/and logic operand)
Start with what the C specification says about taking the address of a bit field. Then don’t take the address of a bit field.
Bitfield behaviour is vendor defined and therefore not portable. Cool idea perhaps but not really necessary or advisable.
bits unlike bytes are not addressable even when you do some_value = (1 << 5) the cpu has to access the whole byte and then extract that bit for you
I don’t see why LinkedIn has become a forum for questions like this. What people trying to prove by posting questions like this. Bitfields are not really portable and in my humble opinion one should use defined data sizes and bit shifts to achieve the same. Macros to define bit set, bit clear and bit test are the way to go. Again only my opinion👍
Bitfields can be dereferenced with pointers, compilation error there . B
B, since address any type needs 4 bytes, here it’s restricted to 3 bits