Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable not initialized as condition c++

I want to do an if like:

if(x has not been initialized)
{...
}

Is this possible? Thanks

like image 294
user2238244 Avatar asked Feb 16 '23 07:02

user2238244


2 Answers

"There is no way of checking of the contents of a variable are undefined or not. The best thing you can do is to assign a signal/sentinel value (for example in the constructor) to indicate that further initialization will need to be carried out."

Alexander Gessler

from here

like image 129
Gengiolo Avatar answered Feb 23 '23 23:02

Gengiolo


To implement that behavior you may use pointers, default initiated to 0.

For example:

int *number = 0;
// ...
if (!number) {
    // do something
}

You may use that trick with any types, not just integers:

Cat *kitty = 0;
// ...
if (!kitty) {
    // do something
}
like image 44
Yurij Avatar answered Feb 23 '23 23:02

Yurij