Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading