Do negative numbers return false in C/C++?

后端 未结 5 1338
傲寒
傲寒 2020-12-04 13:25

When evaluating integers as booleans in C/C++, are negative numbers true or false? Are they always true/false regardless of compilers?

5条回答
  •  自闭症患者
    2020-12-04 13:50

    You can test it yourself by compiling this:

    #include 
    
    int main(int argc, char** argv) {
        if (-1) {
            printf("-1 is true\n");
        } else {
            printf("-1 is false\n");
        }
        return 0;
    }
    

    Results:

    $ gcc -Wall -pedantic test.c -o test-c
    $ g++ -Wall -pedantic test.c -o test-cpp
    $ ./test-c
    -1 is true
    $ ./test-cpp
    -1 is true

    Of course, to answer the second part of your question, "Are they always true/false regardless of compilers?", the only way to be completely sure is to look at the spec. In general though, compilers will warn you if you do something dangerous, and you can see from the output above, that even with "pedantic" warnings, gcc considers this code to be perfectly fine.

提交回复
热议问题