One of the reasons I allmost never get any real work done, I think, is that I allmost allways stumble over small things that I don't understand. And then, instead of pragmatically solving it another way, I stop everything.
This time it's about declaring and initializing integer variables in C++:
Silly me though that !<variable> would return true if the variable was initialized, and false if it wasn't. And for the first two integers in this example - l and h - it seems to work like that. But not for the third, s. The printout of the above is:
int l, h, s;
cout << "Not l!" <<endl;
cout << "Not h!" <<endl;
cout << "Not s!" <<endl;
That's it. Apparently, it has decided that s is indeed intialized, even though it doesn't happen anywhere. If I change the variable declaration to this:
Then the printout is:
So it's obviously the third one that's different. I might be completely off here, of course, since I've barely started looking at C++. Is this a non-valid way to check if a variable is initialized? Even if it is, I'm curious as to why the result is different for the third variable. There's probably a basic and obvious explanation, I know :-)
Well none of them are initialised.
However, all of them will contain some garbage value.
If said garbage value is zero, then !var will return true.
But this is just pure dumb luck at the moment.
> Is this a non-valid way to check if a variable is initialized?
You cannot check via some means in the language if a variable has been initialized or not.
If you want to test if they've been assigned some value or not, initialize them to some invalid input, and then check if they're equal to that.
Elysia: That was going to be my follow-up question. I know that it's possible, but I wondered if it would be a more "tidy" way of doing it. In the example I was playing with, where the values needs to be in a specific range for the program to continue, the solution seems to be to initialize the integers with "wrong" (too high, too low etc.) values. That way I can use a while-loop to wait for input in the target range.
That is typically how you do it. That and have a loop that verifies input to see it is within a sane range. Ensuring a variable it initialized to some non-legit range just makes sure that loop gets started.
Originally Posted by cnewbie1
Of course, you can avoid initializing it altogether and making sure that it is initialized later, with for example, some input before use (a do ... while loop may be appropriate here).