Question

What is the mathematical equivalent equation of following Macro

#define SQ(a) (a*a )
int answer SQ(2 + 3 );

Output is 11 for this case and for

int answer SQ(2 + 4);

is 14 I can't figure out the equation from outputs.

Était-ce utile?

La solution

The macro you defined lacks brackets to keep the arithmetic working as you want. Remember preprocessor macros are doing text replacement solely. So what you'll get from calling it as you shown expands to

int answer (2 + 4 * 2 + 4);

and according operator precedence the result is 14.

Write your macro as

#define SQ(a) ((a)*(a))

to get the result you expected.

Autres conseils

SQ(2 + 4) expands to 2+4*2+4 = 14 because you have not used brackets in your macro. It is a generic macro pitfall for newcomers as macros are not quite safe in this respect as they are just processed by the preprocessor as raw string.

You should write something like this:

#define SQ(a) ((a)*(a))

and that will expand to: (2+4)*(2+4) = 36.

The same logic holds true If you replace 4 with 3, you will get to the 11, and with the corrected macro 25.

That being said, you really should not initialize an integer like that. The general way is to use explicit assignment.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top