简体   繁体   English

预处理器常量评估

[英]Preprocessor constant evaluation

I have a small question about the preprocessor constants in C. I understand what is the goal of this kind of "variable" and how it works.我有一个关于 C 中预处理器常量的小问题。我了解这种“变量”的目标是什么以及它是如何工作的。 However, I have a small question about their evaluation.但是,我对他们的评价有一个小问题。 Let's consider a small example :让我们考虑一个小例子:

#define MY_VARIABLE 5

int main() {
    int test1 = MY_VARIABLE*5;
    int test2 = 5;
    int test3 = MY_VARIABLE*test2;
}

During the preprocessor step, MY_VARIABLE will be replaced by 5 in the code.在预处理器步骤中, MY_VARIABLE将被 5 替换。 My question is: will test1 be computed during the compilation or during the execution ?我的问题是:在编译期间还是在执行期间会计算test1 Is that correct that test3 will be computed during the execution ?在执行期间计算test3是否正确? This question may seem a bit weird and useless but I'm studying a program where this kind of things is done a lot of times and I would like to know if this kind of operation can slow the execution.这个问题可能看起来有点奇怪和无用,但我正在研究一个程序,在这个程序中,这种事情会做很多次,我想知道这种操作是否会减慢执行速度。

As you have already understood, the C preprocessor merely replaces the macros before the actual compilation takes place, therefore I stripped out all preprocessor related stuff.正如您已经了解的那样,C 预处理器仅在实际编译发生之前替换宏,因此我删除了所有与预处理器相关的内容。

In this code no evaluation takes place during execution because the compiler calculates 5*5 during compile time and by inference is can also evaluate all other constants during compilation:这段代码中,在执行过程中没有求值,因为编译器在编译时计算 5*5 并且通过推断它也可以在编译期间求值所有其他常量:

int main() {
    int test1 = 5 * 5;
    int test2 = 5;
    int test3 = 5 * test2;
}

The exact equivalent of the preceeding code fragment is:与前面的代码片段完全等效的是:

int main() {
    int test1 = 25;
    int test2 = 5;
    int test3 = 25;
}

But in following code test3 is evaluated during run time, because the value of test2 cannot be determined during compile time, because it depends on the return value of SomeFunction that can only be known at run time.但是在下面的代码中test3是在运行时求值的,因为test2的值在编译时是无法确定的,因为它依赖于只能在运行时知道的SomeFunction的返回值。

int main() {
    int test1 = 5 * 5;
    int test2 = SomeFunction();        
    int test3 = 5 * test2;
}

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

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