基础备忘:宏和预编译

来源:互联网 发布:阿里布达年代集百度云 编辑:程序博客网 时间:2024/06/02 02:47

#include<iostream>#define MACRO 1<<2const double PI = 3.14;//不能写成const double PI 3.14 using namespace std;int main(){    cout<<MACRO<<endl;    cout<<(MACRO)<<endl;    cout<<PI<<endl;    system("pause");    }

#include <iostream>using namespace std; /*定义带参数的宏时,如果可替代文本一行写不完,可以分成多行,并在每一行的结尾加上连续符号"\",除了最后一行*/#define LESS(x,y) x<y #define SMALL(x,y) { \        if(x<y)\        {\                cout<<"较小值:"<<x<<endl; \                 }\        else \        { \             cout<<"较小值:"<<y<<endl; \             }\             }  #define LEZ(x,y) {cout<<x<<" "<<y;}               int main(){    /*有无分号按宏展开后是否符合c++语法规范来决定。宏是在预编译时处理,而不是在编译期*/     LESS(1,2);//有分号     bool result=LESS(1,2);//有分号     cout<<result<<endl;    SMALL(2,3)//无分号     LEZ(7,8)//无分号     cout<<endl;    system("pause");    }

#include <iostream>using namespace std;#define HANKAI_A(x) iTemp##x //展开后相当于iTempx,##是字符串连接符 //#define HANKAI_B(x)  #@x //展开后相当于'x',x只允许单个字符,在devc++下报错:'#' is not followed by a macro parameter #define HANKAI_C(x)  #x //展开后相当于"x",x允许是多个字符 int main(){    int HANKAI_A(1)=100;    cout<<HANKAI_A(1)<<endl;    //cout<<HANKAI_B(a)<<endl;    cout<<HANKAI_C(abc)<<endl;    cout<<HANKAI_C(HANKAI_A(1))<<endl;    system("pause");    }

#include <iostream>using namespace std;#if !defined(__cplusplus)#error C++ compiler required.#endifint main(){    cout<<"Hello World"<<endl;    system("pause");    }

#include <iostream>using namespace std;#if !defined(__c) //__cplusplus#error C compiler required.#endifint main(){    cout<<"Hello World"<<endl;    system("pause");    }


下面是通过一个范例来说明带参数的宏和函数的区别

#include <iostream>using namespace std;#define Macro(y) ((y)*(y))#define Macro2(y,res) \{ \        res = y*y; \        } int func(int y){    return y*y;    }    int main(){    int i=1;    while(i<=5)         cout<<Macro(i++)<<" ";         cout<<endl;            int j=1,res;    while(j<=5)    {         Macro2(j++,res)  //无分号。只是替换功能。宏没有返回值,这种带{}的宏可以最后一个表达式的值         cout<<res<<" ";         }         cout<<endl;             int k=1;    while(k<=5)         cout<<func(k++)<<" ";         cout<<endl;    system("pause");}

从输出结果来看,使用了函数的使用了带参数的宏得到的结果大不相同。这是因为在函数定义的代码中,函数调用是把实参i的值传给形参y后自增1,然后输出函数值,因此要循环5次。输出1~5的平方。

而在宏定义的代码中调用时,只做代换。调用Macro(i++)的地方被代换为(i++)*(i++)。每次循环后i的值会增加2,因此只做3次循环。

原创粉丝点击