Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Compiles fine with -Wall -Werror. No warnings.


    int x = 1;
    bool y = x;

    # cl.exe /W3 main.c
This code gives a warning on VS2012. But it doesn't give one when the cast is in a loop condition. That is weird.

http://stackoverflow.com/a/31552168/5994461

This stackoverflow message talks about the specs for C11, and the first comment adds information on the C++03 spec. It seems that implicit cast from integer to boolean is allowed... under all circumstances... depending on what specification the compiler is following :D

For future references, I'll just summarize this as "C and C++ are minefields". We'll just add that to the list of WTF behaviors.

By the way, if you think that "C has had bool for 19 years" [the C99 spec specifically]. You clearly didn't work in C for long enough with a large variety of tools. The world is bigger than just GCC.


> But it doesn't give one when the cast is in a loop condition. That is weird.

I believe that the justification for that is that you'll often want to do e.g.

    while (node) {
      node.val += 3;
      node = node->next;
    }
Implicit conversion of a type into a bool is pretty useful here, or for e.g.

    while (std::cin >> x >> y) { ... }


I imagine the warning is following the rules for explicit constructors/operators in C++: an if condition is considered an "explicit" call to an `operator bool`. http://en.cppreference.com/w/cpp/language/explicit




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: