I defined a few constants in a way showed below
constexpr int a = 1;
constexpr int b = 2;
My question is whether all arithmetic and bitwise operations that only use a and b will be considered as constexpr by the compiler?
For example, I'm wondering whether compiler is guaranteed to calculate the expression for c compile time? If not, is there a way to ask for compile time calculations?
c = (a + b) & (a | b);
My question is whether all arithmetic and bitwise operations that only use
aandbwill be considered asconstexprby the compiler?
Such an expression is usable in constexpr context, with a few exceptions (anything that causes undefined or implementation-defined behavior must be avoided, e.g. bitwise right shift on a negative quantity, division by zero, overflow of a signed type).
For example, I'm wondering whether compiler is guaranteed to calculate the expression for c compile time?
Only if the expression is used in a context where a compile time context is required.
If not, is there a way to ask for compile time calculations?
That's what the constexpr keyword applied to a variable will do. Assuming that you can't just add the qualifier to c itself because it is used as a variable (reassigned later based on runtime data, for example) you can still force the calculation to be constexpr:
constexpr auto cvalue = (a + b) & (a | b);
c = cvalue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With