Is there any difference between bool foo = true and bool foo = 1?

In C++, is there any difference between assigning a bool to true and assigning it to 1(or any non-zero integer)?

I have seen many competitive programmers use 1 instead of true even when the code is written in advance, so I want to know if there is any benefit besides simply being faster to type.

>Solution :

… and assigning it to 1(or any non-zero integer)?

In your simple example, the effect will be the same.

// all true:
bool foo = true;
bool bar = 1;
bool baz = 123;

is there any difference?

The one I come to think about is readability/intent. Assigning 1 to a variable displays that the programmer intends this to be a variable carrying a numeric value. After a closer inspection of the code, I will notice that it’s assigned to a bool (and I will promptly change it to true before continuing to read the code).

In the not so simple cases, you’ll instead get a surprise:

#include <iostream>

void foo(bool) { std::cout << "bool\n"; }
void foo(int) { std::cout << "int\n"; }   // oups someone added an overload

int main() {
    foo(1);   // I use 1 instead of true because it's so much shorter
}

Leave a Reply