c/c++ 中#ifndef和#endif的作用及使用

有时候我们在编程的时候,希望有些代码在我们需要时编译,不需要时不编译,也就是让它快速注释,这时候即可以考虑#ifdef和#endif,它们会使我们的编译器进行选择性编译。使用方法如下:

  1. #include<iostream>  
  2. #include<cstdio>  
  3.     
  4. #define DEBUG  //至于这个DEBUG的名字,你们可以随心定义
  5.     
  6. using namespace std;  
  7. int main(){  
  8. #ifdef DEBUG  //如果你前面改掉了DEBUG的名字,呢么这里记得要改
  9.     cout<<"Hello World"<<endl;  
  10. #endif  
  11.     return 0;  
  12. }  

如果你们的电脑没问题的话,呢么输出一定是下面这个:

这时我们在#define DEBUG前面打上注释符:

  1. #include<iostream>  
  2. #include<cstdio>  
  3.     
  4. //#define DEBUG  
  5.     
  6. using namespace std;  
  7. int main(){  
  8. #ifdef DEBUG  
  9.     cout<<"Hello World"<<endl;  
  10. #endif  
  11.     return 0;  
  12. }  

运行结果如下:

如果您这时还不懂的话,您只需要记住#ifdef 和 #endif是选择性编译组,这时您再返回看以上程序。

原文地址:https://www.cnblogs.com/Chicago/p/9435457.html