No Value-command?

Hello!
I was just wondering if there is a command that tests if a variable has a value or not. As an example:

1
2
3
4
5
int x = 5;

while(x has a value){
   do something;
}


In this case the program would "do something" forever since x's value doesn't change.

1
2
3
4
5
int x;

while(x has a value){
   do something;
}


And in this case nothing would happen. Do you get what I mean? Anyway, is there such a command?
1
2
3
4
int x = 5;
while (x == a_value){
   cout << "x equals a_value;
} 


as you said, this would hang the app, as it's an infinite loop.

In your second case:

1
2
3
4
5
int x;

while(x has a value){
   do something;
}


it is said that x is uninitialized. That doesn't mean it has no value . It just means that you don't know its value. It's garbage, it may be 7 or 100 or probably some big number 1989381231. int x designs a lacation in memory that will be interpreted as an int. Since you don't inicialize it, what is there inside that memory location is completely unknown. But it's something.
Okay, I'm sorry then. I meant, is there a way to test if a variable is initialized or not? :)
There is no way in C++ of knowing if a variable is initielized or not. You should check its value using the comparison operator if (x == a_value)
All variables always have a value, initialized or not. You have to use another variable to remember if it was initialized, and std::optional/boost::optional does that for you.
Last edited on
If you always initialise your variables, you won't have to check...
... Did you really think that I was going to use it for that? I wanted a loop to continue until the last part of an array was initialized.
If you find the question answered, you should mark the thread as solved.
Topic archived. No new replies allowed.