I keep seeing warnings about undefined behavior in C, including criticism of C: A Modern Approach. What does undefined behavior actually mean, and is the book still a reasonable place to start?
What is undefined behavior in C, and is C: A Modern Approach still good for beginners?
Answers
Undefined behavior means the C standard places no requirements on what happens when a program does a particular invalid thing. The program might crash, appear to work, produce strange results, or behave differently after you change compiler settings.
For example, closing a file with fclose and then calling fclose again on that same closed stream is undefined behavior. The first call ends the stream's lifetime, so the second call is not a valid way to use it.
The tricky part is that a result that looks correct doesn't prove the code is valid. A compiler can optimize on the assumption that undefined behavior does not occur, and the effects aren't necessarily confined to the line that caused it.
Reply to this answer
One distinction that trips people up is unspecified behavior versus undefined behavior. C does not generally specify the order in which function arguments are evaluated. If the arguments don't interfere with one another, either order can be valid. Depending on a particular order is still a bad idea, but the lack of a specified order alone isn't undefined behavior.
On the other hand, something like func(i++, i++) modifies i twice without the required sequencing between those modifications. That is undefined behavior, not merely a choice of which increment happens first.
Reply to this answer
Signed integer overflow is another example worth knowing about. If an int already holds its maximum value, adding one to it has undefined behavior. Don't assume it must wrap around to a negative number just because that happens on a particular machine.
This matters for optimization too. The compiler can reason that a valid signed addition has not overflowed, so a check written on the assumption that signed overflow wraps may not work as intended.
Reply to this answer
Yes, it's reasonable to use C: A Modern Approach as a beginner. One assessment of the book is that it teaches readers to avoid undefined behavior, though the material here doesn't establish how thoroughly it covers every case.
I wouldn't put off learning C over a vague warning about the book. Work through the explanations and exercises, and when a particular example is said to be problematic, check the exact code and the reason given.
_p38+drimvori.4:
That helps. I'll keep using it and look for the specific examples behind any criticism rather than assuming the whole book is unsafe.
Reply to this answer
Add your answer
Answers are reviewed before publication.
5m~gimbalratchet_714:
So the practical fix is to do the changes in separate statements before the call, rather than trying to predict which argument gets evaluated first.