0

I am a newbie to C++ and got stuck with this.

#include<iostream>
int main()
{
    bool a = 2;
    bool e { 4 }; //error
    std::cout << a << e;
    std::cin.get();

}

I get error as 'initializing': truncation from 'int' to 'bool'. Why does a work and not e?

ccdq23
  • 7
  • 2

1 Answers1

2

A narrowing conversion is (roughly speaking) a conversion between built-in types that might need to truncate or take a modulus on some values because the destination type is not capable of suitably representing a given source value if known at compile time, or some possible source values if the value is not known at compile time.

So conversion from the known value 2 or 4 to a bool is a narrowing conversion, since a bool can't really represent those numbers, only 0 or 1.

Ever since C++11, it has been illegal for a program to require a narrowing conversion on any value found within { curly braces } used for aggregate initialization or list-initialization.

A narrowing conversion is still allowed when the source is not in curly braces, such as your bool a = 2;.

aschepler
  • 70,891
  • 9
  • 107
  • 161