Answer the question
In order to leave comments, you need to log in
Why is #define deprecated?
Scott Myers' book "Using C++ Effectively" gives an example of a bad use of the #define directive:
And further what this can lead to:
int a = 5, b= 0
max(++a, b); // a увеличится дважды
max(++a, b+10); // a увеличится один раз
Answer the question
In order to leave comments, you need to log in
Because
1. there is no type control
2. there is no scope restriction, such as namespaces.
3. the macro is expanded by substitution at the place of use, i.e. there will be inserted code
((a) > (b) ? (a) : (b)) which will turn into ((++a) > (b+10) ? (++a) : (b+10))
4 .macros are hard to debug
5.an incorrectly written macro will compile to something you don't understand. For example, if you remove the same brackets
as without them, the expression x = max(a, b) + 10 will open; ?
x = a > b ? a : b+10;
for max, most likely, it makes no sense to wrap the parameters in brackets, quite common, although you can probably think of something to break without them. It's just accepted, due to the fact that macros can be inside the expression and how their non-trivial parameters will be revealed there is not clear.
For example
#include <iostream>
#define mymax(a,b) a>b?a:b
#define mul(a,b) a*b
int main()
{
std::cout << mymax(5, 10) << std::endl; // Ошибка компиляции
std::cout << mul(5+5, 10) << std::endl; // Неожиданно на выходе 55, а не 100
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question