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 4 of 10.

MELVIN said:   1 decade ago
How is it possible?

Vsreddy said:   10 years ago
Hi friends we will see above two program:

int main()
{
int p=10,a;
a=++p + p++;
printf("%d",a);
}

->We will o from left to right first p value is incremented it becomes 11. So right now p=11;.

->Next p value is incremented but it is post increment so in expression still value of p is 11.

So final answer is a = ++p + p++;

a = 11+11;

Answer: 22.

But after completion of expression p value is 12 remember.

Neju said:   10 years ago
int main(){
int b,a=10;
b=a++ + ++a;
printf("%d%d%d%d",b,a++,a,++a);
}

1. b = 10+12 = 22 (since a++ is 10 (11 in memory) ++a will be 12).

2. a++ 12 in memory 13.

3. a 13.

4. ++a 14.

The output 22 12 13 14. Why its not like this?

Praveen said:   10 years ago
Explain once again sir!

b=a++ + ++a + ++a; if a=10.

Here answer is 34 because,

Step 1: Since expression is left associate. So 1st a++ execute
here a++ = 10, cause of post prefix then it increment by 1 and store in memory, now in memory a = 11.

Step 2: Now in expression most preference given to pre increment
so both ++a store 11+1 = 12.

Step 3: Now b = a++ + ++a + ++a = 10+12+12 = 34 execute.

Here just you calculate step 2 only what about 3rd step here last ++a value is why 12, not 13 please explain.

Sri said:   10 years ago
When I tried to compile the following exp in gcc i.e.

main()
{
int a;
a=3/2*2;
printf("%d",a);
}

It gives me the answer as 2 how to solving this?

Vansh said:   10 years ago
What is value of c if a = 4, b = 7?

c = ++a/10*a--%--b/++a.

Kumar said:   9 years ago
What is the value of b if a=2;

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

Can explain this solution.

Amala said:   9 years ago
C evaluates printf() statement from right to left.if we want to make it evaluates from left to write then we have declare the function to be PASCAL.

int b,a=10;
b=a++ + ++a;
printf("%d %d %d %d",b,a++,a,++a);

Output:
22, 13, 13

Abhi said:   9 years ago
Why not option c? if as the same precedence.

Lavanya said:   9 years ago
Thank you @Siva, I got clear answer.


Post your comments here:

Your comments will be displayed after verification.