macros

the output of this question is 12 6 12 ... please explain

1
2
3
4
5
6
7
8
9
10
  #define FUN(x,y) ((x)>(y))?(x):(y);
int main()
{
int i=10,j,k;
j=5;
k=0;
k=FUN(++i,j++);
cout<<i<<j<<k;

}
The macro will be expanded before compilation. It will just replace the FUN macro with what it was defined as (replacing x with ++i and y with j++). That gives the following program.
1
2
3
4
5
6
7
8
int main()
{
	int i=10,j,k;
	j=5;
	k=0;
	k=((++i)>(j++))?(++i):(j++);;
	cout<<i<<j<<k;
}


All the parentheses on line 6 makes me somewhat confused so here it is with the parentheses removed:
k = ++i > j++ ? ++i : j++;

First the expression ++i > j++ will be evaluated. ++i will increment i and return the value of i after it was incremented (11). j++ will increment j and return the value of j before it was incremented (5). 11 is greater than 5 so the expression returns true.

The way that the ternary operator (cond ? exp1 : exp2) works is that if the condition is true it will evaluate and return the value of the first expression (the one after the question mark), otherwise it will evaluate and return the value of the second expression (the one after the colon).

In this case the condition was true so ++i is the expression that will be executed. This increments i once again and returns the new value of i, so this is the value that is assigned to k.

i was 10 from the start and was incremented twice so it will now have the value 12.
j was 5 from the start and was incremented once so it will have value 6.
k was assigned the new value of i so k will have the same value as i, that is 12.
Last edited on
thanks i was making mistake in macro expansion... :)
let the preprocessor do it for you (-E for gcc)

¿what's the point of the exercise?
Topic archived. No new replies allowed.