Seems like this would be a duplicate, but maybe it is just so obvious it hasn\'t been asked...
Is this the proper way of checking if a variable (not pointer) is init
With C++17 you can use std::optional to check if a variable is initialized:
#include
#include // needed only for std::cout
int main() {
std::optional variable;
if (!variable) {
std::cout << "variable is NOT initialized\n";
}
variable = 3;
if (variable) {
std::cout << "variable IS initialized and is set to " << *variable << '\n';
}
return 0;
}
This will produce the output:
variable is NOT initialized
variable IS initialized and is set to 3
To use std::optional
in the code snipped you provided, you'll have to include the std::optional<...>
to the respective variable declarations:
#include
class MyClass
{
void SomeMethod();
std::optional mCharacter;
std::optional mDecimal;
};
void MyClass::SomeMethod()
{
if ( mCharacter )
{
std::cout << *mCharacter; // do something with mCharacter.
}
if ( ! mDecimal )
{
mDecimal = 3.14159; // define mDecimal.
}
}