首页 > 解决方案 > 我可以让 C 函数使用外部变量,而不让它修改它们吗?

问题描述

如果我有一个 C 函数使用的全局变量“x”

int foo() {

    extern int x;

    return x;

}

我可以禁止 foo 修改 x 吗?即以与下面的替代方法相同的方式对待 x?

int foo(const int x) {

    return x;

}

标签: cglobal-variables

解决方案


方法一:常量拷贝

#define HorribleHackStart(Type, Name) \
    Type HorribleHackTemp = Name; { const Type Name = HorribleHackTemp;

#define HorribleHackEnd \
    }

int foo(void)
{
    HorribleHackStart(int, x)
    ... Here x is an unchanging const copy of extern x.
    ... Changes made to x (by other code) will not ge visible.
    HorribleHackEnd
}

方法二:指针

int foo(void)
{
    #define x (* (const int *) &x)
    ... Here x is effectively a const reference to extern x.
    ... Changes made to x (by other code) will be visible.
    #undef x
}

注释

我不会在生产代码中使用其中任何一个,但如果您想编译代码以测试函数内部是否违反了 x 的 const 要求,它们可能会很有用。


推荐阅读