Macros in C / C++
I define a function as a macro:
#define DIVIDE(x, y) x / y
And I call it in the code:
z = DIVIDE(1 + 1, 1 + 1);
As a result, I get:
z = 3;
And it should be:
z = 1;
What is the reason?
0
Author: Nicolas Chabanovsky, 2010-12-10
3 answers
The fact is that the macro definition
#define DIVIDE(x, y) x / y
When calling
z = DIVIDE(1 + 1, 1 + 1);
Expanded by the preprocessor into the expression
z = 1 + 1/1 + 1;
Which gives
z = 3;
The macro is expanded first and then calculated, not the other way around.
5
Author: stanislav, 2010-12-12 10:37:20
The problem is that you are using macros incorrectly.
- Take the contents of the macro in parentheses.
- Take all arguments in parentheses.
Then the macros will be executed correctly:
#define DIVIDE(x, y) ((x) / (y))
Get the result:
z = DIVIDE(1 + 1, 1 + 1) = ((1 + 1) / (1 + 1)) = (2 / 2) = 1;
4
Author: Алексей Сонькин, 2011-02-24 22:37:49
And in general-it is better not to use macros, but to define your own template function for division.
template <class Type>
Type my_divide(Type x, Type y)
{
return x / y;
}
Almost certainly, this function will be built-in, so that the overhead of calling it will be minimal. And at the same time, there will be no disadvantages inherent in macros.
0
Author: gecube, 2011-06-12 10:45:15