The usage of #undef and its meaning


[cpp]  view plain copy  
 
  1. #include <iostream>  
  2. usingnamespace std;   
  3.   
  4. intmain  ()  
  5. {  
  6. #define MODI 10  
  7.     cout << MODI << endl;  
  8. #undef MODI  
  9.     cout << MODI + 1 << endl;  
  10.     return 0;  
  11. }  
The compiler will report an error to the line cout << MODI + 1 << endl;.

The reason is what #undef does:

When you run out of a macro, such as MODI, you don't want the following code to use this MODI, then you can #undef it, then if you use the MODI macro again, the compiler will report an error.

A common practice is:

[cpp]  view plain copy  
 
  1. #define MAX 50  
  2. #include "common.h"  
  3. #undef  MAX  

This makes the macro MAX available only in common.h.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326050331&siteId=291194637