是常数C EX pressions在编译或运行时进行评估? [英] Are constant C expressions evaluated at compile time or at runtime?

查看:152
本文介绍了是常数C EX pressions在编译或运行时进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写的的#define 的执行使用其他preprocessor常量的操作,是每个宏出现在运行时间计算的终值?这是否取决于优化的编译器,或者是一个标准的范围之内?

If I write a #define that performs an operation using other preprocessor constants, is the final value computed each time the macro appears at runtime? Does this depend on optimizations in the compiler, or is it covered under a standard?

例如:

#define EXTERNAL_CLOCK_FREQUENCY    32768
#define TIMER_1_S                   EXTERNAL_CLOCK_FREQUENCY
#define TIMER_100_MS                TIMERB_1_S / 10

请问操作的一十分之三万二千七百六十八的每一个我用的是TIMER_100_MS宏时间在运行期间发生?

Will the operation 32768 / 10 occur at runtime every time I use the TIMER_100_MS macro?

我想避免如下:

#define EXTERNAL_CLOCK_FREQUENCY    32768
#define TIMER_1_S                   EXTERNAL_CLOCK_FREQUENCY
#define TIMER_100_MS                3276


摘要

一个编译器需要能够因为他们需要在编译时间计算之类的东西数组的大小来评价整型常量前pressions。然而,标准只说他们可以 - 而不是必须 - 这样做。因此,只有一个脑死亡的编译器不会计算在编译时整型常量前pressions,但是汇编输出为一个非常规的编译器进行简单的检查将核查每宗个案。


Summary

A compiler is required to be able to evaluate constant integral expressions because they are necessary for calculating things like array sizes at compile time. However, the standard only says they "can" -- not "must" -- do so. Therefore, only a brain-dead compiler would not evaluate a constant integral expressions at compile time, but a simple check of the assembly output for an unconventional compiler would verify each case.

推荐答案

宏是简单的文本替换,所以在你的例子在程序中写 TIMER_100_MS 是一个奇特的方式写一十分之三万二千七百六十八

Macros are simply textual substitution, so in your example writing TIMER_100_MS in a program is a fancy way of writing 32768 / 10.

因此​​,问题是当编译器将评估一十分之三万二千七百六十八,这是一个整型常量前pression。我不认为标准要求任何特定的行为在这里(因为运行时和编译时的评价实际上是没有区别),但是任何半路出家的编译器在编译时将对其进行评估。

Therefore, the question is when the compiler would evaluate 32768 / 10, which is a constant integral expression. I don't think the standard requires any particular behavior here (since run-time and compile-time evaluation is indistinguishable in effect), but any halfway decent compiler will evaluate it at compile time.

这篇关于是常数C EX pressions在编译或运行时进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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