dear there,
I need to print all initialized variables, and some the uninitialized variables got printed, which mess up the output. how do I detect it before send it to printf or cout? thanks.
dear there,
I need to print all initialized variables, and some the uninitialized variables got printed, which mess up the output. how do I detect it before send it to printf or cout? thanks.
You could always just write
int foo = 0;
and then the problem goes away. This type of declaration is called initialization.
A rule of thumb is to declare variables near first use, where you are able to initialise them appropriately.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Not always, since sometimes you assign some value to it before use (not necessarily initialization).
Good compilers and debuggers will also warn or break if you use an uninitialized variable (Visual Studio [IDE + compiler + debugger] does it for sure, GCC [compiler] highly likely as well, not about others).
GCC only emits the warning when you compile with optimizations and warnings on, because the flow analyzer necessary for this warning isn't run without optimizations.
As a programmer, you cannot and should not detect uninitialized variables at runtime, the reason being that looking at the value of the variable invokes undefined behavior. You're supposed to statically prove that a variable cannot be uninitialized by the time it's used. Which isn't all that hard, really.
(And by the way of terminology, "uninitialized" in this context means "never having received a (initial) value. Yes, Elysia, another case where common usage conflicts with C++-specific terminology. But in this case, the C++-specific terminology doesn't actually exist: "not having an initializer" isn't called "uninitialized", it's called "not having an initializer".)
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
As whiteflags said, you can (and should) set the variable to 0 immediately upon declaration. However, if 0 is a potential value for your variables, an alternative is to set it to some other value (like -1) that will be a signal to the system that the variable is unitialized.
Code:short iArray[5]; //initalizing array for(char x=0;x<5;x++) { iArray[x]=0; } //output values that are initialized //zero means the variables are NOT initialized for(char x=0;x<5;x++) { if(iArray[x]) { cout<<x<<": "<<iArray[x]<<endl; } }