Variable not initialized as C ++ condition

I want to do if you want:

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

Is it possible? Thanks

+4
source share
6 answers

"There is no way to check the contents of an undefined variable or not. The best you can do is assign a signal / sentinel value (for example, in the constructor) to indicate that further initialization will be performed."

Alexander Gessler

from here

+4
source

You can use pointers to implement this behavior, the default is 0.

For instance:

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

You can use this trick for any type, and not just for integers:

 Cat *kitty = 0; // ... if (!kitty) { // do something } 
+3
source

a) For primitive data types, such as int, float, it cannot be recognized if it is initialized or not.

b) For pointers you can check if its nullptr or not

 if(ptr != nullptr) { } 

c) For a custom class, you need to introduce a bool element that can be set to true in the constructor so that we can use it to check if the object is initialized or not.

 if(obj.isInitialized()) { } 
+1
source
  • If you have a pointer, you can use nullptr to mean “not initialized”.
  • If you don't have a pointer, you can use boost::optional<T> (or std::optional<T> when it becomes available).
  • Otherwise, the naive flag <<23> must be executed. optional<T> is just an encapsulation of this flag.
+1
source

With C ++ - 11, you can consider storing a variable using smart pointers. Declare yor x (assuming x will be int ) as

 std::shared_ptr<int> x; 

When assigning the variable x use

 x = std::make_shared<int>(newValueOfX); 

and then you can determine if x ever been assigned by checking

 if (this->x) { ... } 

See Checking variable initialization for a more detailed example.

0
source

Well, something like this will work for pointers. Say:

 int* x = NULL; //initialize if(x == NULL) { //dostuff } 

or simply

 if(!x) { //dostuff } 

Not sure if there is a way for a regular int though

EDIT: Now that I think about it, Lutyan is right. This will be undefined behavior. As the others said, you must initialize a known value.

-1
source

Source: https://habr.com/ru/post/1485098/


All Articles