-2

I'm learning C programming and currently about operators.I'm little confused in a problem from sometimes.please have a at the imageimage1

The program is:

#include<stdio.h>
int main()
{
    int a=9,b=5,c;
    c=a*b++ + --a;
    printf("%d",c);
    return 0;
}


I think the output should be 48 but it is showing 53.Since --a have the higher precedence so it should be evaluated first and bis post increment so the value of b will be change after the termination of the statement.(correct me if i'm wrong).
Please help .Thankyou in advance.

ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42
  • 1
    Precedence does not equal evaluation order in C. For example, the compiler might decide to first increment `a`, and then evaluate both instances of `a`. – fuz Oct 05 '15 at 10:18
  • I didn't get what you are saying please elaborate . –  Oct 05 '15 at 11:11
  • 1
    Your reasoning about inferring evaluation order from precedence is wrong. Precedence only tells the compiler where to put parentheses, it does not tell the compiler in which order to evaluate things. – fuz Oct 05 '15 at 11:44

2 Answers2

1

This is a classic case of unspecified behavior. Here it is not specified which side of the plus operator should be evaluated first.

If the left side of + is evaluated first then you get 53 as --a is executed after a*b++.

If the right side of + operator is evaluated first then you get 48 as a-- is executed first reducing a to 8 then a*b++ gets executed yielding 40.

So, it depends on the compiler implementation that which side is evaluated first and hence it can yield different answers on different compilers.

You can read up more about unspecified behavior here

Community
  • 1
  • 1
Nishant
  • 2,571
  • 1
  • 17
  • 29
0

yes strange! but here is a possible scenario for what your compiler is doing.

int a=9,b=5,c;
/*
c=a*b++ + --a; // 

*/

c=(a*b)++; // multiplication then addition ;

the compiler uses the temp result of (a*b) then increment the tmp result (which is now useless) the result remains 45;

then a is decremented before adding it to the final result

c=45+(9-1)= 45+8=53

milevyo
  • 2,165
  • 1
  • 13
  • 18