r/learncpp • u/TridentBoy • Jun 19 '21
Primer C++ (5th Edition) states some rules of the language that don't follow my experience.
I'm beginning my studies in C++, using Windows and the g++ compiler (Version 10.3.0).
Right at the beginning there is an exercise that asks the value of an uninitialized variable. It expects us to say that an int defined inside "int main" is undefined. But in my tests it's always initialized as 0.
Other part is the rules for identifier. It says that we can't have two consecutive underscores, nor begin with an underscore followed by a capital letter. But I've tested both and it compiles and runs without error.
Is this happening because my compiler is newer than the book?
8
u/Ahajha1177 Jun 19 '21
Uninitialized variables: it may often be zero, but it is not guaranteed to be. Relying on uninitialized values being zero will almost certainly come to bite you in the ass one day.
Double leading underscores: there's nothing in the language itself that disallows them, in fact, quite the opposite, they're reserved for use by compiler-specific implementations of things. For example, I believe feature test macros, the __cpluscplus macro, and any internal variables used by standard libraries use double leading underscores, to prevent potential abuse from user-defined variables or macros in the global namespace. So you can do this, but if something using that name already causes issues, it's on you.
6
u/[deleted] Jun 19 '21
Regarding the uninitialised variable thing, I think it is compiler dependent but regardless, it is a very bad idea to get used to.
3
u/patatahooligan Jun 19 '21
Having a value equal to zero is one of the infinite possible outcomes of undefined behavior. That's the thing with undefined behavior. You can't disprove its existence just because you got a result that validated your assumption.
Again, that's undefined behavior. It might clash with a compiler's internal variables/macros. It might not be parsed correctly. Or it just might work.