Vishesh Mehta
Vishesh Mehta

Reputation: 9

How the following relational expression written in if-else statement is understood by the C Compiler?

I am unable to understand why this code is displaying 20 30 40 as output. Can anyone explain how the relational expression written in if statement is understood by the C Compiler ?

This is the image of code of the C Program

#include <stdio.h>

int main()
{
   int i = 20, j = 30, k = 40;
   if (i > j == k)
   {
       printf("%d %d %d ",--i,j++,++k);
   }
   else
   {
       printf("%d %d %d ",i,j,k );
   }

   return 0;
}

Output:

20 30 40

Upvotes: 0

Views: 58

Answers (2)

fatihsonmez
fatihsonmez

Reputation: 103

first thing to consider is operator precedence. the operator > is evaluated before the operator == and it returns a value. in this case, i > j is wrong so it returns zero. then it checks if zero equals to k which is 40 and it isn't. so it goes to else branch.

Upvotes: 2

Garf365
Garf365

Reputation: 3707

According operator precedence i > j == k is executed as (i > j) == k

So i > j is executed first, returning a boolean (here, false, ie 0) And result is compared to k, which is not equal to 0. Condition is than false, so else part of condition is executed

Upvotes: 1

Related Questions