inline内联函数

C++中的const常量可以替代宏常数定义,如:

const int A = 3; è #define A 3

C++中是否有解决方案替代宏代码片段呢?(替代宏代码片段就可以避免宏的副作用!)

 

C++中推荐使用内联函数替代宏代码片段

 

C++中使用inline关键字声明内联函数

 

 

内联函数声明时inline关键字必须和函数定义结合在一起,否则编译器会直接忽略内联请求。

 

带参数的宏和函数调用

 

#include <iostream>
using namespace std;

//带参数的宏
#define MYFUNC(a,b) ((a)<(b)?(a):(b))

inline int myfunc(int a, int b)
{
    return a < b ? a : b;
}

int main(void)
{
    int a = 1;
    int b = 3;
    
    //一般情况不要使用++,--做函数参数
    int c = myfunc(++a,b); //a=2,b=3,c=2
    //int c = MYFUNC(++a,b);  //a=3,b=3,c=3
                        //宏替换并展开 ((++a)<(b)?(++a):(b))
    
    printf("a=%d\n",a);
    printf("b=%d\n",b);
    printf("c=%d\n",c);
    
    cout<<"hello..."<<endl;
    
    return 0;    
}

 

posted @ 2018-09-23 16:25  Liu_Jing  Views(823)  Comments(0Edit  收藏  举报