Hacker News new | ask | show | jobs
by dkersten 5051 days ago
Before I give you an example, I will define what the term undefined behavior means by quoting the standard - Section ยง1.3.12 (of the C standard, not the C++ standard which is horribly ginormous and hard to read):

    behaviour, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

    Undefined behaviour may also be expected when this International Standard omits the description of any explicit definition of behavior.
The reason undefined behavior is dangerous is that the standard does not guarantee any particular behavior and the implementation is free to do whatever it wants - ignore it, give an error message, delete everything on your hard drive.. whatever.

The two most commonly cited piece of undefined behavior is modifying a variable twice in one sequence point. The standard says:

    Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.
This code snippet invokes undefined behavior:

    a = b++ * ++b;
because b is modified twice within one sequence point. More information here http://stackoverflow.com/questions/4176328/undefined-behavio...

-----

For more real world examples of where undefined behavior may bite you in the ass in C++, take a look at Washu's simple C++ quiz. It's only four questions: http://www.scapecode.com/2011/05/a-simple-c-quiz/

Take a moment to answer the questions before looking at the answers.

Once you've done that, here are three more quizzes by the same guy - these ones are about OOP in C++, so may be much more relevant to your question: http://www.scapecode.com/2011/05/c-quiz-2/ and http://www.scapecode.com/2011/05/c-quiz-3/ and http://www.scapecode.com/2011/05/c-quiz-4/