Quote:Original post by Cromulent
Quote:Original post by ToohrVyk
and never ever try to write code which you do not already know for certain is correct.
Unless you mathematically prove the correctness of your code (I seem to remember it is a part of some maths centric computer science degrees / PhDs) you are never 100% sure your code is correct and even if your code is 100% correct then you are not sure that the code it relies on is 100% correct (i.e the operating system).
Being 100% correct is not the point: this would involve a complete program analysis that is generally not even computable (reduces to the halting problem or similar). What is important is that no undefined behavior appears: this is much easier to determine, simply by traversing the code in a linear fashion and determining if a given statement breaks any language rules.
C++ has a lot of pitfalls that may not seem immediately obvious to an average beginner, which mostly stem from odd features that are inconsistent. For instance, you can null a pointer by assigning a zero integer constant to it, but not by assigning it zero at compile time. And so, even extremely simple code bears the risk of being inconsistent:
int *ptr = 0; // correct!memset(ptr, 0, sizeof(ptr)); // incorrect!ptr = condition ? 0 : new int; // well?
When writing a line such as the third one, it's necessary to check whether the 'zero' in that expression will remain an integer (thus assigning ptr a runtime value of zero, which is not a null pointer) or if it's converted to a null pointer value beforehand (for those who care, 5.16 §5 says it works as expected).