Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C equivalent operator creating confusion

Tags:

c

Program 1:

#include<stdio.h>
void main()
{
    int i=55;
    printf("%d %d %d %d\n",i==55,i=40,i==40,i>=10);
}

Program 2:

#include<stdio.h>
void main(){
    int i = 55;
    if(i == 55) {
        printf("hi");
    }
}

First program give output 0 40 0 1 here in the printf i == 55 and output is 0 and in the second program too i ==55 and output is hi. why

like image 966
Vishvendra Singh Avatar asked Jan 06 '14 07:01

Vishvendra Singh


1 Answers

In the first example, the operators are evaluated in reverse order because they are pushed like this on the stack. The evaluation order is implementation specific and not defined by the C standard. So the squence is like this:

  1. i=55 initial assignment
  2. i>=10 == true 1
  3. i==40 == false (It's 55) 0
  4. i=40 assignment 40
  5. i==55 == false (It's 40) 0

The second example should be obvious.

like image 151
Devolus Avatar answered Oct 19 '22 22:10

Devolus