C++字面量算术运算是否编译期求值?含C#、Java对比及场景分析
Arithmetic Operations on Literals & Built-in Types in C++: Compile-Time vs Run-Time Evaluation
Great question! Let's break down exactly when these operations get evaluated in C++, focusing on your two key scenarios.
1. When used to define built-in types
C++ draws a clear line here based on whether the expression qualifies as a constant expression:
- Compile-time evaluation (guaranteed by the standard):If the arithmetic operation uses only compile-time-known values (like literals,
constexprvariables, or results ofconstexprfunctions), the compiler will compute the result during compilation. For example:
You won't see any arithmetic instructions in the compiled assembly here—these values are hardcoded directly.int x = 10 + 7; // x is set to 17 at compile time constexpr int base = 5; int y = base * 3; // y is 15, computed during compilation - Run-time evaluation: If the expression includes values that can only be determined at runtime (like non-
constvariables, or calls to non-constexprfunctions), the operation happens when the program runs. For example:int get_input() { /* reads user input */ return 42; } int z = get_input() - 10; // Subtraction happens at runtime int a = 6; int b = a / 2; // Division runs at runtime since 'a' isn't a compile-time constant
2. When used as function arguments
This depends on the function type and whether the argument expression is a constant expression:
- Compile-time evaluation (guaranteed):If you're passing the result of a constant expression to a
constexprfunction, the entire calculation happens at compile time. For example:constexpr int multiply(int a, int b) { return a * b; } int result = multiply(4, 5); // multiply(4,5) is 20, computed at compile time - Potential compile-time (optimization) or run-time: For non-
constexprfunctions, even if you pass literal values, the C++ standard doesn't require the compiler to evaluate the arithmetic at compile time. That said, most modern compilers will perform constant folding (a common optimization) and compute the result during compilation. For example:
However, if any part of the argument expression is a runtime value, the arithmetic will definitely happen at runtime:int add(int a, int b) { return a + b; } int sum = add(3, 6); // Compiler will likely set sum to 9 at compile time, but it's not requiredint c = 8; int product = multiply(c, 2); // Multiplication runs at runtime
A quick note: C++11 and later expanded the rules for constant expressions, so even more complex arithmetic (like nested operations, or calls to simple constexpr functions) can be evaluated at compile time as long as they meet the standard's requirements.
内容的提问来源于stack exchange,提问作者Herpes Free Engineer
相关产品推荐
相关产品推荐

