The result of evaluating relational operators

Suppose we have an expression like

(x > 5) 

in C. Is there any guarantee provided by the language / standard that the expression will be evaluated to 0 when it is false and 1 when it is true?

+5
source share
2 answers

Yes, it is guaranteed by the standard.

According to standard C11 document, chapter 6.5.8, paragraph 6, [Relational operator]

Each of the operators < (less), > (more), <= (less than or equal) and >= (greater than or equal) should give 1 if the specified relation is true and 0 if it is false . The result is of type int .

Update: same chapter and paragraph for C99 .

+12
source

In gcc, it will be evaluated as one and zero. Consider the following program

  #include <stdio.h> int main(void) { int a = 3; int b = 4; if((a > b) == 0) printf("a > b is false\n"); if((a < b) == 1) printf("a < b is true\n"); return 0; } 

He outputs

 a > b is false a < b is true 
0
source

Source: https://habr.com/ru/post/1213444/


All Articles