C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

How expression a==b==c (Multiple Comparison) evaluates in C programming?

Since C language does not support chaining comparison like a==b==c; each equal to operator (==) operates on two operands only. Then how expression a==b==c evaluates?

According to operators associativity equal to operator (==) operates from left to right, that means associativity of equal operator (==) is left to right.

Expression a==b==c is actually (a==b) ==c, see how expression (a==b) ==c evaluates?

  • (a==b) will be compared first and return either 1 (true) or 0 (false).
  • Then value of variable c will be compared with the result of (a==b).





Consider the following program

#include <stdio.h>
int main(){
	int a,b,c;
	a=b=c=100;
	
	if(a==b==c)
		printf("True...\n");
	else	
		printf("False...\n");
	
	return 0;	
}

Output

False...

How output is "False..."?

See the program, the values of a, b and c is 100 and you are thinking how condition is false here and why output is "False..."?

The expression is a==b==c which will evaluates like (a==b)==c now what will be the result?

  • The result of (a==b) is 1 (i.e. true).
  • And (1)==c will be 0 (i.e. false) because the value of c is 100 and 100 is equal not to 1.

COMMENTS