现在的位置: 首页 > 综合 > 正文

C++学习之宏

2018年04月29日 ⁄ 综合 ⁄ 共 997字 ⁄ 字号 评论关闭
# include<cstdio>
# include<iostream>

using namespace std;

# define OK 123
# define PI 3.1415926
# define S PI*y*y  //完成了宏的嵌套,也就是说在展开S这个宏的时候,PI已经被代换了

int main(void)
{
    int y;cin>>y;
    cout<<S<<endl;
    cout<<"OK"<<endl;//加了引号后,预处理程序将不对OK进行宏代换
    cout<<OK<<endl;



    return 0;
}
***********************************************************

带参数的宏

/*
    需要注意带参数的宏和函数的区别
        1.带参数的宏的形参变量不会分配内存单元,因此不必做类型说明,
        这是与函数的情况不同的,因为函数中的情况往往需要对形参做类型
        说明,并且形参将占据一定的内存空间.
        2.在带参的宏当中,只存在符号的代换,不存在值传递的问题.
*/

# include<cstdio>
# include<iostream>

using namespace std;

# define MAX(a,b) (a>b)?a:b //用宏名MAX表示条件表达式(a>b)?a:b

int main(void)
{
    int x,y,max;
    cin>>x>>y;
    max = MAX(x,y);
    //max = MAX(x,y); 将变成 max = (a>b)?a:b;
    cout<<max<<endl;



    return 0;
}

带参数的宏的几种特例

# include<cstdio>
# include<iostream>

using namespace std;

# define SQ(y) (y)*(y)
# define SQ(y) y*y // 相当于 a+1*a+1 != (a+1)*(a+1)

int main(void)
{
    int a;
    int sq;
    cin>>a;
    sq = SQ(a+1);//注意这条语句的执行过程,
                //首先用a+1去替换y,然后用(a+1)*(a+1)去替换SQ(a+1)
    cout<<sq<<endl;

    return 0;
}

# define SQ(y) ((y)*(y))

//想想,如果这里使用 # define SQ(y) (y)*(y)为什么得不到预期的结果
int main(void)
{
    int a,sq;
    cin>>a;
    sq = 16/SQ(a+1);
    cout<<sq<<endl;


    return 0;
}











抱歉!评论已关闭.