内联与 宏

#include <iostream>
using namespace std;
inline double square(double x){return x*x;};  //内联函数

int  main()
{
    double a,b;
    double c=13.0;
    a=square(5.0);      //5.0*5.0=25
    b=square(4.5+7.5);   //(4.5+7.5)(4.5+7.5)=144
    cout<<"a="<<a<<",b="<<b<<"\n";
    cout<<"c="<<c;
    cout<<", c square="<<square(c++)<<"\n";  //square(c++)=square(14)=13*13=169  c=14 
    cout<<"Now c="<<c<<"\n";

    getchar();
    return 0;
}

内联函数和常规函数一样,是按值来传递参数的,如果参数为表达式,则函数将传递表达式的值

#include <iostream>
using namespace std;
inline double square(double x){return x*x;};
#define  SQUARE(X)  X*X

int  main()
{
    double a,b;
    double c=13.0;
    a=SQUARE(5.0);  //5.0*5.0=25
    b=SQUARE(4.5+7.5); //4.5+7.4*4.5+7.5=45.75
    cout<<"a="<<a<<",b="<<b<<"\n";
    cout<<"c="<<c;
    cout<<", c square="<<SQUARE(c++)<<"\n";   //c++*c++=13*13=169
    cout<<"Now c="<<c<<"\n"; //c=15

    getchar();
    return 0;
}

宏不能按值传递,而是通过文本替换来实现的

posted @ 2018-07-30 14:41  小雨滴答  阅读(127)  评论(0编辑  收藏  举报