【问题标题】:C Language - different definitions of function due to global variablesC 语言 - 由于全局变量,函数的不同定义
【发布时间】:2020-12-12 18:07:35
【问题描述】:

我是否可以有一个由于某些全局变量的值而定义不同的函数 - 例如称为“s”? 如果 s 等于 0,它应该接受两个整数,否则接受一个字符。

我尝试过使用 C 预处理器,但似乎在进行预处理时无法访问全局变量。


# include <stdio.h>

int s = 1;
# if (s == 0)
void f(int x, int y);
# else
void f(char x);
#endif

int main(){
    if (s == 0) f(0, 1);
    else f('z');
    return 0;
}

令人惊讶的是,在上面的代码中 f 将被定义为接受两个参数,这在逻辑上是不期望的。 我也不想改变main函数。

【问题讨论】:

  • 你不能在预处理器中使用变量。在预处理器条件s == 0 中, s 未定义,因此等于零。

标签: c function c-preprocessor signature


【解决方案1】:

你可以这样做

    # include <stdio.h>
    
    #define S
    
    # ifdef S
    void f(int x, int y);
    # else
    void f(char x);
    #endif

    int main(){
        
        # ifdef S
        f(0, 1);
        # else
        f('z');
        #endif

        return 0;
    }

如果你想运行“else”版本,你只需将 S 的定义放在评论中//#define S

【讨论】:

    猜你喜欢
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多