Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of boolean variables

Tags:

c++

boolean

This question might seem naive (hell, I think it is) but I am unable to 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 compiled and executed, it always prints 0.

The problem is that is not what I'm expecting it to do: as far as I know, a local variable has no initialization value, and I believe that a random byte has more chances of being different rather than equal to 0.

What am I missing?

like image 259
Cynical Avatar asked May 31 '13 12:05

Cynical


People also ask

How do you initialize a boolean variable in Java?

To display Boolean type, firstly take two variables and declare them as boolean. val1 = true; Now, use if statement to check and display the Boolean true value. if(val1) System.

How do you initialize a boolean variable in C++?

In C++, we use the keyword bool to declare this kind of variable. Let's take a look at an example: bool b1 = true; bool b2 = false; In C++, Boolean values declared true are assigned the value of 1, and false values are assigned 0.

How do you initialize a boolean variable in Python?

If you want to define a boolean in Python, you can simply assign a True or False value or even an expression that ultimately evaluates to one of these values. You can check the type of the variable by using the built-in type function in Python.

Are booleans initialized as false?

The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers.


1 Answers

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

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

A glvalue (3.10) of a non-function, non-array type T can be converted to a prvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the prvalue is the cv-unqualified version of T. Otherwise, the type of the prvalue is T.

like image 130
Andy Prowl Avatar answered Oct 01 '22 03:10

Andy Prowl