Does the C standard explicitly indicate truth value as 0 or 1?

前端 未结 7 1535
日久生厌
日久生厌 2020-12-08 06:14

We know that any numbers that are not equal to 0 are viewed as true in C, so we can write:

int a = 16;

while (a--)
    printf(\"%d         


        
7条回答
  •  渐次进展
    2020-12-08 07:05

    I've programmed in many languages. I've seen true be 1 or -1 depending on the language. The logic behind true being 1 was that a bit was either a 0 or 1. The logic behind true being -1 was that the ! operator was a one's complement. It changed all the 1's to 0's and all the 0's to 1's in an int. So, for an int, !0 = -1 and !(-1) = 0. This has tripped me up enough that I don't compare something to be == true, but instead compare it to be != false. That way, my programming style works in every language. So my answer is to not worry about it, but program so that your code works correctly either way.

提交回复
热议问题