3 ms·
The questions are about the C language, not any particular implementation thereof. Question 2 requires you to know that different compilers may at times legally
by wtallis 12y ago
The questions are about the C language, not any particular implementation thereof. Question 2 requires you to know that different compilers may at times legally do different things with the same piece of code. Answering question 2 does not require you to know which compiler is in use. Instead it requires you to think in the mindset of someone trying to write portable code that will work as intended with any compliant compiler.
In this case, the code is invalid because it invokes undefined behavior, and the compiler is allowed to do literally anything. The author of a portable C program is not allowed to rely on any particular behavior. I don't have any of the ISO C standards docs handy, but I'm quite certain that they all agree here. The (probably hypothetical) compiler in use here is apparently trying to apply several heuristics that are useful in other situations but fail here because there is no right answer.
In general, the C standards avoid requiring a specific behavior where choosing to require a specific behavior could hurt portability. Most C compilers make use of their leeway to interpret things in a manner that helps make bad code run and many compilers make promises beyond those required by the standard to aid in writing non-portable code.
- fizixer 12y ago> ... the compiler is allowed to do literally anything ... and yet he makes the claim that "bar() is invoked" which is not only incorrect (bar may or may not be invoked), but also misleading for C newbies who are actually trying to learn something by reading this article. Hence my original comment.
- Gibbon1 12y agoI think my point is dereferencing a pointer address zero is 'undefined' but here is the rub, what happens is entirely out of the optimizer and compilers control because it depends on the context that the program is run under. One can't determine at compile time what will happen. In fact the compiler can't make any assumptions about a pointer whose value has been hard coded. uint8_t b = (uint8_t) 0x30; // 0x30 is the address of PORT D on an AVR Atmega8
- wtallis 12y ago"bar() is invoked" is not incorrect. It's perfectly legal for a compiler to produce this result. It's just not mandatory that all compilers do so. There's nothing wrong with the question postulating that a particular compiler behaves this way; the point of the question is to remind the programmer that they have to expect and be prepared for variance between compilers when it's permitted by the standard.