Explore BrainMass

Macro processing in C/C++

This content was STOLEN from BrainMass.com - View the original, and get the already-completed solution here!

The following code fragment produces the correct result sometimes and sometimes it does not. Explain what is happening and why.

#include <stdio.h>
#define max(a,b) ((a) > (b) ? (a): (b))
void main(void)
int i = 0;
int j = 0;
int a = 3;
int b = 4;
int c = 6;
int d = 5;
i = max(a,b);
j = max(c,d);
printf("i = %i, j = %in",i,j);
i = max(a++, b++);
printf("a = %i, b = %in",a,b);
j = max(c++,d++);
printf("c = %i, d=%in",c,d);

© BrainMass Inc. brainmass.com December 20, 2018, 8:58 am ad1c9bdddf

Solution Preview

Given code fragment will produce unexpected results in case of

i = max(a++, b++);


j = max(c++,d++);

Things would have worked as expected if max(...) were a function call. However it is a macro call, and thus given code fragments become following after preprocessing step during compilation.

i = ((a++) > (b++) ? (a++) : (b++));


j = ((c++) > (d++) ? (c++) : (d++));

Before these code fragments execute,
(a,b) : (3,4)
(c,d) : ...

Solution Summary

Response first points out the code fragments that will produce unexpected results, and then goes on explaining in complete detail (and step-by-step manner), why it is so.