我如何搜索此问题(范围内的宏与内联函数)

时间:2019-04-01 08:33:02

标签: c++ scope macros inline

我对范围有一些疑问。

我认为宏的行为类似于复制和粘贴,内联函数与此相似,但不相同。

但是,我不知道为什么这段代码对我有影响。

我不知道要搜索哪个关键字,请给我宣布一些要搜索的关键字。

感谢您阅读。

'''
inline int add(int a, int b)
{
    return a + b;
}

int main()
{
    int num1;

    num1 = add(10, 20);

    printf("%d\n", num1);

    return 0;
} // is same as below
'''
int main()
{
    int num1;

    num1 = int add(int a=10, int b=20)
    {
        return a + b;
    };

    printf("%d\n", num1);

    return 0;
}
'''
#define xtest() cout<<x<<endl

int x=0;

inline void test(){
    cout<<x<<endl;
}

int main(void){
    int x=10;
    test();
    cout<<x<<endl;
    xtest();
    {
        int x = 20;
        test();
        cout<<x<<endl;
        xtest();
    }
    return 0;
}

我了解xtest(){cout << x << endl}的行为相同并且结果正确,但是为什么test()的行为却不同?

1 个答案:

答案 0 :(得分:1)

标记为inline的功能与非inline的功能只有一种不同:它们可以以多个转换单元(=源文件)定义,而不会引起违反“一个定义规则”(=链接器错误)的情况)。这就是全部。在所有其他方面,它们的行为与其他任何函数一样。它们与宏完全不同。