Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do bitwise operations of constexpr result in constexpr?

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);
like image 817
TruLa Avatar asked Feb 23 '26 09:02

TruLa


1 Answers

My question is whether all arithmetic and bitwise operations that only use a and b will be considered as constexpr by 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;
like image 96
Ben Voigt Avatar answered Feb 25 '26 22:02

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!