2

On page 1057 of Programming Principles and Practice Using C++, Second Edition, Bjarne Stroustrup discusses a problem with Function-like macros.

He starts with an example. The macro below:

#define MAX(x, y) ((x)>=(y)?(x):(y))

used in the following line:

double dd = MAX(aa++, 2);

substitutes to become:

double dd = ((aa++)>=(2)?(a++):(2));

About this example, he explains:

On the other hand, not all the parentheses in the world could save the second expansion. The macro parameter x was given the value aa++, and since x is used twice in MAX, a can get incremented twice. Don't pass an argument with a side effect to a macro.

As it happens, some genius did define a macro like that and stuck it in a popular header file. Unfortunately, he also called it max, rather than MAX, so when the C++ standard header defines

template<class T> inline T max(T a, T b) {return a<b?b:a;}

the max gets expanded with the arguments T a and T b and the compilers sees

template<class T> inline T ((T a)>=(T b)?(T a):(T b)) {return a<b?b:a;}

The compiler error messages are "interesting" and not very helpful. In an emergency, you can "undefine" a macro:

#undef max.

Bjarne Stroustrup's story sounds like it would be a well-known one in the C++ community, however, I couldn't find anything more written about it online. Bjarne Stroustrup's frustration here suggests that this particular header created backwards compatibility problems developing C++.

What was the header Bjarne refers to in his story?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
mana
  • 545
  • 4
  • 12
  • 1
    Likely Windows: https://learn.microsoft.com/en-us/windows/win32/multimedia/max – Tas Sep 21 '20 at 04:57
  • 2
    The old [`minmax.h`](https://stackoverflow.com/questions/62394972/what-is-minmax-h-in-c) header is still present in the latest Windows UCRT (though it's not used/included in any of the other headers). Yet older Windows SDKs had a dedicated [`NOMINMAX`](https://stackoverflow.com/questions/4913922/possible-problems-with-nominmax-on-visual-c) macro to sanitize `windows.h`. In fairness, these are cases I happen to be familiar with, certainly not the only ones, and not necessarily what the book was referring to. – dxiv Sep 21 '20 at 05:04

0 Answers0