Initializing Boolean Variables

This question may seem naive (hell, I think it is), but I cannot find an answer that satisfies me.

Take this simple C ++ program:

#include<iostream> using namespace std; int main () { bool b; cout << b; return 0; } 

When compiling and executing, it always prints 0 .

The problem is that this is not what I expect from it: as far as I know, a local variable does not matter initialization, and I believe that a random byte is more likely to be different than 0 .

What am I missing?

+4
source share
5 answers

This behavior is undefined because you are using the value of an uninitialized variable. You cannot expect anything from a program with undefined behavior.

In particular, your program requires the so-called lvalue-to-rvalue conversion when initializing the operator << parameter from b . Paragraph 4.1 / 1 of the C ++ 11 standard indicates:

The value gl (3.10) of a non-function type without an array T can be converted to prvalue. If T is an incomplete type, a program that requires this transformation to form poorly. If the object to which the glvalue belongs is not an object of type T and is not an object of a type derived from T , or if the object is not initialized, the program that requires such a conversion has undefined behavior . If T is a non-class type, the prvalue type is a cv -qualified version of T Otherwise, the prvalue type is T

+11
source

Undefined behavior; there is no requirement that he be assigned a random value and, of course, not evenly distributed.

What is likely to happen is that the memory allocated for the process is initialized by the operating system to zero initialization, and this is the first time this byte is used, so it still contains zero.

But, like all undefined behavior, you cannot rely on it, and there is little point in thinking about the details.

+6
source

As Andy said, this behavior is undefined. I think the fact that you are so lucky and always get 0 is an implementation. Probably, when the program starts, the stack is empty and clean (initialized with zeros). It so happens that you get zero when placing the variable there.

+1
source

This can be guaranteed to succeed in your current implementation (as others have said, it may initialize the stack with zeros), but it will also be guaranteed to fail, for example, using the Visual C ++ debug build (which initializes the local variables 0xCCCCCCCC).

0
source

C ++ static and global variables are initialized by default, as C89 and C99 say, and in particular arithmetic variables are initialized to 0.

Automatic variables are indeterminate , which on C89 and C99 in 3.17.2 mean that they are either an undefined value or a trap representation. A Trap representation in the context of a bool type may mean 0 - this is compiler specific.

0
source

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


All Articles