Ionut Alexandru
Ionut Alexandru

Reputation: 806

consteval vs constexpr on variables

Is there any difference between constexpr and consteval ?

 consteval int x1 = 2;
 constexpr int x2 = 5;

Is it better to use constexpr than consteval?

Upvotes: 28

Views: 13853

Answers (1)

catnip
catnip

Reputation: 25388

The standard actually says:

The consteval specifier shall be applied only to the declaration of a function or function template.

So your first example should not compile.


However, you can put consteval or constexpr on functions:

constexpr int foo (int x) { return x; }
consteval int bar (int x) { return x; }

constexpr when applied to a function is merely largely advisory (see Davis Herring's comment) - it says to the compiler, evaluate this function call at compile time if you can.

consteval, on the other hand, is mandatory - it says to the compiler, generate an error if you can't evaluate this function call at compile time.

Live demo

Upvotes: 52

Related Questions