常量 C 表达式是在编译时还是在运行时计算? [英] Are constant C expressions evaluated at compile time or at runtime?

查看:35
本文介绍了常量 C 表达式是在编译时还是在运行时计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我编写一个使用其他预处理器常量执行操作的 #define,那么每次宏在运行时出现时都会计算最终值吗?这是否取决于编译器中的优化,还是包含在标准中?

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 宏时都会在运行时发生 32768/10 操作吗?

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

<小时>

总结

编译器需要能够计算常量积分表达式,因为它们是在编译时计算数组大小等内容所必需的.然而,标准只说他们可以"——而不是必须"——这样做.因此,只有脑残编译器不会在编译时计算常量积分表达式,但对非常规编译器的汇编输出进行简单检查就可以验证每种情况.


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 是编写 32768/10.

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

因此,问题是编译器何时计算32768/10,这是一个常数积分表达式.我不认为标准在这里需要任何特定的行为(因为运行时和编译时的评估实际上是无法区分的),但任何中规中矩的编译器都会在编译时对其进行评估.

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 表达式是在编译时还是在运行时计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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