-2

I was going through my C learning by writing small pieces of code and one new question came up

I have written a small piece of code

#include<stdio.h>
#include<conio.h>
#define SUM(a) (a+a)
main()
{
  int w,b=5;
  w=SUM(b++);
  printf("%d\n",w);
  printf("%d\n",b);
  getch();     
}

What i was thinking that it will display the output as

10

6

but it is showing

10

7

Can someone explain why ,i am using Visual Studio 2008

beastboy
  • 157
  • 1
  • 3
  • 11

1 Answers1

2

because when you do

w=SUM(b++);

the macro will be replaced by:

w= b++ + b++;

now, if b=5 then you do twice b++ and get b=7

Edit

after reading MSalters comment i did some searching and found out that as he said this code couse UB.

as says here:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70