Macro problem

Hi

Can someone help me understand why the value of SQUARE (x) is 49?

I am using Visual C ++ 6.0.

#define SQUARE(X) X * X int main(int argc, char* argv[]) { int y = 5; printf("%d\n",SQUARE(++y)); return 0; } 
+4
source share
4 answers

Neil Butterworth, Mark and Paul are right.

SQUARE (++ y) expands to ++ y * ++ y, which doubles the value of y.

Another problem you might run into: SQUARE (a + b) expands to a + b * a + b, which is not (a + b) * (a + b), but a + (b * a) + b. You should take care to add parentheses around elements when necessary when defining macros: #define SQUARE (X) ((X) * (X)) is slightly less risky. (Ian Kemp wrote this first in his comment)

Instead, you can use the built-in template function (no less efficient at runtime), such as:

 template <class T> inline T square(T value) { return value*value; } 

You can check if it works:

 int i = 2; std::cout << square(++i) << " should be 9" << std::endl; std::cout << square(++i) << " should be 16" << std::endl; 

(no need to write

 square<int>(++i) 

because the int type is implicit for i)

+15
source

Since the macro expands to:

 ++y * ++y 

which gives undefined behavior in C ++ - the result can be anything. This very well-known problem should be covered in any decent textbook that covers the use of macros. Which one are you using?

+14
source

Macros are not functions: they simply change the text of the program. This operation is called preprocessing, and it is automatically performed before compiling the code. People write macros to save their time and introduce some variability into the source code.

When you write SQUARE(x) , no actual function call occurs, only the text changes. The operation is pretty dumb, so you need to take extra precautions in cases like yours. See other answers for an explanation of your case.

+5
source

Since macros do textual substitution, so the code you wrote expands to

 printf("%d\n",++y * ++y ); 

and then the order of operations is undefined, so the compiler sees 2 increments, and then multiplication

Therefore, be careful with macros to make better use of functions that, since the compiler can expand the string, will no longer be executed.

Secondly, do not assume what will happen if you increase and use variables

+4
source

All Articles