C Programming - Expressions - Discussion

Discussion Forum : Expressions - General Questions (Q.No. 1)
1.
Which of the following is the correct order of evaluation for the below expression?
z = x + y * z / 4 % 2 - 1
* / % + - =
= * / % + -
/ * % - + =
* % / - + =
Answer: Option
Explanation:
C uses left associativity for evaluating expressions to break a tie between two operators having same precedence.
Discussion:
92 comments Page 10 of 10.

Siva said:   1 decade ago
@Shashanka.

a = 10;

Step1:
a++ = 11; (now a=11);

Step2:
++a = 11+1=12; (now a=12);

Step3:
++a = 12+1=13;

So the result is 11+12+13=36;

And then finally you got 36.

Poonamchandra said:   1 decade ago
@Jayesh.

Your program:

#include<stdio.h>
int main(){
int i=5,j=5,y,x;
x=++i + ++i + ++i;
y=++j + ++j + ++j;
printf("%d %d %d %d",x,y,i,j);
return 0;
}

Will surely give the output 22 22 8 8

This is because in case of incr/decr operation performed after =(equal to) operator, all prefix incr/decr are carried out first and allot value to all variables that is the value of variable at L.H.S. of =, and then for variable used after = will be incr/decr as same no of time equal to the postfix incr/decr..

example:

void main()
{
int a=5, b;
b=a++ + ++a + ++a;
printf("%d",b);
}

In line
b=a++ + ++a + +aa;

There are two prefix increment so a's value will be incremented two times, e.i. a=7 and then a will be allotted to every a variable in that line, so that b's value will be something like this:

b=7+7+7, i.e b=21 and a=7,

But we left one postfix increment operator a++, so increment a by one
, then a=8;

At final, a=8, b=21.

Try some examples and your doubt will be surely be cleared.


Post your comments here:

Your comments will be displayed after verification.