简体   繁体   English

预处理程序#if指令

[英]Preprocessor #if directive

I am writing a big code and I don't want it all to be in my main.c so I wrote a .inc file that has IF-ELSE statement with function and I was wondering can it be written like this: 我正在编写一个大代码,但我不希望所有这些都在main.c中,所以我写了一个.inc文件,其中包含带有功能的IF-ELSE语句,我想知道是否可以这样写:

#if var==1
process(int a)
{
    printf("Result is: %d",2*a);
}
#else
process(int a)
{
    printf("Result is: %d",10*a);
}
#endif

I tried to compile it but it gives me errors or in best case it just goes on the first function process without checking the var variable (it is set to 0). 我尝试编译它,但它给了我错误,或者在最佳情况下,它只是在第一个函数进程中进行而未检查var变量(将其设置为0)。

The preprocessor doesn't "know" the value of any variable, because it does its work even before compilation, not at runtime. 预处理器不会“知道”任何变量的值,因为即使在编译之前(而不是在运行时)它也会执行其工作。

In the condition of a preprocessor #if you can only evaluate #define 'd symbols and constant expressions. 在预处理条件#if你只能评估#define倒是符号和常量表达式。

The particular example you are showing can be simply converted to: 您所显示的特定示例可以简单地转换为:

printf("Result is: %d", (var == 1 ? 2: 10) * a);

This is what you want: 这就是你想要的:

process(int a)
{
   if (var == 1)
      printf("Result is: %d",2*a);
   else
      printf("Result is: %d",10*a);
}

It is important to remember that the preprocessor is its own program and not a part of the program you are writing. 重要的是要记住,预处理器是其自己的程序,而不是您正在编写的程序的一部分。 The variable "var" (or whatever var represents here) is not in the the namespace of the preprocessor's identifiers. 变量“ var”(或此处表示的var)不在预处理器标识符的名称空间中。

Just to complete. 刚刚完成。 For a standard conforming compiler your code would always be correct. 对于符合标准的编译器,您的代码将始终是正确的。 In #if expression evaluations all identifiers that are not known to the preprocessor are simply replaced with 0 (or false if you want). #if表达式求值中,预处理器不知道的所有标识符都简单地替换为0 (如果需要,则为false)。 So in your particular case, if var is just a variable and not a macro, the result would always be the second version of your function. 因此,在您的特定情况下,如果var只是变量而不是宏,则结果将始终是函数的第二个版本。

For the error that you report for MS: I did know that the MS compilers aren't standard conforming, but I wasn't aware that they don't even fulfill such basic language requirements. 对于您为MS报告的错误:我确实知道MS编译器不符合标准,但是我不知道它们甚至不能满足这种基本语言要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM