C预处理程序#if表达式 [英] C preprocessor #if expression

查看:144
本文介绍了C预处理程序#if表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在C语言中可以与#IF预处理程序一起使用的表达式类型,我有些困惑。我尝试了以下代码,但无法正常工作。请说明并提供可与预处理程序一起使用的表达式的示例。

I am a bit confused on the type of expression we can use with the #IF preprocessor in the C language. I tried the following code, and it isn't working. Please explain and provide examples for expressions that can be used with the preprocessor.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int c=1;

#if c==1
    #define check(a) (a==1)?a:5
    #define TABLE_SIZE 100
#endif

int main()
{
    int a = 0, b;
    printf("a = %d\n", a);
    b = check(a);
    printf("a = %d %d\n", a, TABLE_SIZE);
    system("PAUSE");
    return 0;
}


推荐答案

预处理器不能使用以下变量表达式中的C程序-它只能作用于预处理程序宏。因此,当您尝试在预处理器中使用 c 时,您不会得到预期的结果。

The preprocessor cannot use variables from the C program in expressions - it can only act on preprocessor macros. So when you try to use c in the preprocessor you don't get what you might expect.

但是,您也不会得到错误,因为当预处理器尝试评估未定义为宏的标识符时,它将该标识符视为值为零。

However, you also don't get an error because when the preprocessor tries to evaluate an identifier that isn't defined as a macro, it treats the identifier as having a value of zero.

因此,当您点击此代码段时:

So when you hit this snippet:

#if c==1
#define check(a) (a==1)?a:5
#define TABLE_SIZE 100
#endif

预处理器使用的 c 与C程序中的变量 c 无关。预处理程序将查看是否为 c 定义了一个宏。既然没有,它将评估以下表达式:

The c used by the preprocessor has nothing to do with the variable c from the C program. The preprocessor looks to see if there's a macro defined for c. Since there isn't, it evaluates the following expression:

#if 0==1

这当然是错误的。

由于您似乎没有使用在程序中使用变量 c ,您可以执行以下操作以使行为与您要尝试的一致:

Since you don't appear to use the variable c in your program, you can do the following to get behavior in line with what you're trying:

#define C 1

#if C==1
#define check(a) (a==1)?a:5
#define TABLE_SIZE 100
#endif

(请注意,我也做了宏名称要大写,以符合宏名称的约定。)

(Note that I also made the macro name uppercase in keeping with convention for macro names.)

这篇关于C预处理程序#if表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆