Macro expansion in context of arithmetic expression?
c, c++
Solution
`#define` expansions kick in before the compiler sees the source code. That is why they are called pre-processor directives, the processor here is the compiler that translates C to machine readable code.
So, this is what the macro pre-processor is passing on to the compiler:
`SQ(2 + 3)` is expanded as `(2 + 3*2 + 3)`
So, this is really `2 + 6 + 3` = `11`.
How can you make it do what you expect?
- Enforce the order of evaluation. Use (), either in the macro definition or in the macro call. OR
- Write a simple function that does the job
Problem
I saw this below code in an website. I could not able to understsnd how the result is coming as `11`, instead of `25` or `13`. Why I am thinking `25` because `SQ(5) 5*5` or `13` because `SQ(2) = 4;` `SQ(3) = 9;` may be final result will be `13 (9 + 4)` But surprised to see result as `11`. How the result is coming as `11`? ``` using namespace std; #define SQ(a) (a*a) int main() { int ans = SQ(2 + 3); cout << ans << endl; system("pause"); } ```