Scope of macro puzzle

2020-05-11 10:13发布

问题:

#include <iostream>
using namespace std;

void sum(){
#define SUM(a,b) a+b
}

int main(void){
   int a = 10; 
   int b = 20; 
   int c = SUM(a,b);
   int d = MUL(a,b);
   cout << c << endl;
   cout << d << endl;
   return 0;
}


void mul(){
#define MUL(a,b) a*b
}

The problem gives an error with MUL macro. But runs fine with SUM macro. Why is this happening?

回答1:

That's because you define the SUM macro before calling it.

It does not have anything to do with the fact that it is defined in a function, i.e. it is accessible on the entire file, bellow its definition.



回答2:

Macros know nothing about function scope. The scope of a macro starts at the #define and ends at an #undef or the end of the compilation unit, whichever happens first.

To use a macro, the code must be in the macro's scope - like the SUM macro in the example.

The MUL macro is not expanded inside main, because its #define has not been seen yet. A macro can not be forward declared, just #define'd, and declaring the function "containing" the macro has nothing to do with macro scope.



标签: c++ macros