简体   繁体   English

使用静态/全局const原语的计算是否在编译时进行?

[英]Do calculations with static/global const primitives occur in compile time?

const int thing = 1234;

int func( int hello )
{
    return hello / (thing*123+321);
}

Is (thing*123+321) computed in compile time? (thing*123+321) 在编译时计算的?

If thing was a user defined type with int operator* would it also happen in compile time? 如果thing是具有int operator*的用户定义类型,它是否还会在编译时发生?

If thing was a float or double would it also happen in compile time? 如果thing是float或double,那么它也会在编译时发生吗?

If I forcibly change thing in runtime would (thing*123+321) be unchanged? 如果我在运行时强制更改thing ,则(thing*123+321)不变吗?

There's no guarantee that it will be, but any optimizing compiler will precompute this value. 无法保证会如此,但是任何优化的编译器都会预先计算该值。 It will probably turn that division operation into a multiplication by a precomputed reciprocal value too. 它也可能会将除法运算乘以预先计算的倒数。

In general, constant expressions can and usually will be computed at compile time. 通常, 常量表达式可以并且通常将在编译时进行计算。 Since you can and if you do use constant expressions as template arguments, there's actually no way around that. 既然可以并且如果确实使用常量表达式作为模板参数,那么实际上是没有办法解决的。

The big question is now what constitutes a constant expression. 现在最大的问题是什么构成一个常量表达式。 In C++98/03, your thing would qualify as one, but a constant function of thing would not, since there's no way to tell the compiler that a function is "pure" in that sense. 在C ++ 98/03中,您的thing将被视为一个thing ,但thing的恒定功能将不被视为一个thing ,因为无法从某种意义上告诉编译器函数是“纯”的。

Some compilers offer extensions (such as GCC's attributes "pure" and "const"), but that's outside the scope of the language. 一些编译器提供了扩展(例如,GCC的属性 “ pure”和“ const”),但这超出了语言的范围。 C++11 introduces the explicit constexpr keyword, which allows you to declare all sorts of expressions as constant and thus eligible for compile-time evaluation. C ++ 11引入了显式constexpr关键字,该关键字使您可以将各种表达式声明为常量,从而可以进行编译时评估。 (For instance, GCC is built with the GMP and MPFR libraries in order to perform those compile-time computations to any degree of precision, so as to be able to target any platform.) (例如,GCC是用GMP和MPFR库构建的,以便以任意精度执行那些编译时计算,从而能够针对任何平台。)

Is (thing*123+321) computed in compile time? (thing * 123 + 321)是在编译时计算的吗?

Yes. 是。

hello / (thing*123+321); 你好/(thing * 123 + 321);

In this case, the full expression is computed at runtime. 在这种情况下,将在运行时计算完整表达式。 since the argument in your function hello is unknown at until you run the program. 因为您的函数hello的参数在运行程序之前是未知的。

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

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