Tuesday, 25 August 2009

A Macro Pitfall Question

Assuming that two macros are defined in the following way
#define max1(a,b) a < b ? b : a
#define max2(a,b) (a) < (b) ? (b) : (a)

what would be the value of x in the following cases:
x = max1(i += 3, j);
x = max2(i += 3, j);

and why?

Assume that initial value of i = 5 and j = 7 in both the cases. What is the value of i and j after the Macro?

Answer:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
In case of max1, x = 12, i = 12 and j = 7. The reason being the substitution will happen like this:
i += 3 < j ? j : i += 3
which using operator precedence rules and language rules means:
i += ((3 < j) ? j : i += 3). Since 3 < 7, i = i + j = 12 which is the same as x.

In case of max2, x = 11, i = 11 and j = 7. The reason being the substitution will happen like this:
(i += 3) < (j) ? (j) : (i += 3). Since 5+3 = 8 which is > 7, i+=3 will be executed again (2nd time) so 5+6 = 11 which is the value of i and x.

No comments:

Post a Comment