Scope of macro puzzle

2020-05-11 09:51发布

#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?

标签: c++ macros
2条回答
劫难
2楼-- · 2020-05-11 10:02

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.

查看更多
够拽才男人
3楼-- · 2020-05-11 10:11

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.

查看更多
登录 后发表回答