📜 ⬆️ ⬇️

When the variable bool is not true and not false at the same time

Recently read the code and stumbled upon about such a fragment.

bool *t = new bool[X][Y]; //   switch (t[M][N]) { case true: //   break; case false: //   break; default: //   break; } 

The question immediately arises: why do we need the default branch? If the variable is not true, then it is false. A classmate said: "For debugging." I think: what is there to debug? But not everything is so simple.

I run. The code in the default branch is executed. The very first assumption - forgot to put a break. I carefully re-read the code - everything is in order. I start it in the debugger and notice that the default branch is executed right away, but it does not even enter the true or false branch. I decide to view the value of the variable. Visual Studio 2012 running on Windows 7 shows 205. Suppose. I began to learn the pros recently, so I decided to do a bit of experience: I created a boolean variable and assigned it 205. The branch is true. While I was pondering over this problem, a classmate found a solution to this problem: it turns out the array was not initialized. After initialization, the problem disappeared. Now I have a question: is there really a problem in the switch? For the sake of verification, I decided to conduct the following experiment.

 #include <iostream> using namespace std; int main() { bool *t = new bool[1]; switch (t[0]) { case true: cout << "true\n"; break; case false: cout << "false\n"; break; default: cout << "superposition\n"; break; } if(t[0] == true) { cout << "true\n"; } else if(t[0] == false) { cout << "false\n"; } else { cout << "superposition\n"; } if(t[0]) { cout << "true\n"; } else if(!t[0]) { cout << "false\n"; } else { cout << "superposition\n"; } delete[] t; return 0; } 

The option with a switch or the first option with if allows you to define an un-initialized boolean variable. The second option with if never enters the third option.
')
How to create such a Schrödinger variable? Create a dynamic or static array. Use it before initialization. And also, the most delicious thing is that you can copy this undefined value, even into a scalar variable. Where it can be useful - you decide.

It is also interesting that if you insert before checking:

 char a = t[0]; t[0] = a; 
then the variable will finally become true. And if you write
 bool a = t[0]; t[0] = a; 


then nothing will change.

Later, I repeated the experience on Visual Studio 2013 with 5 service packs running on Windows 7. There, the debugger says that the uninitialized variable is true, but despite this, the true block does not enter. She also says that the default branch is not needed, since all possible labels are already set. But despite this, it goes into the default block.

In Linux, this feature does not appear.

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


All Articles