18

Is there any difference between constexpr and consteval ?

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

Is it better to use constexpr than consteval?

cigien
  • 57,834
  • 11
  • 73
  • 112
Ionut Alexandru
  • 680
  • 5
  • 17
  • 1
    I've rolled-back the question, as it was nicely answered below. Please ask a new question if you want, otherwise you may end up wasting other's time spent in writing an answer, which is not ideal. – cigien Oct 16 '20 at 20:22

1 Answers1

34

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 cannot evaluate this function call at compile time.

Live demo

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
  • 5
    `constexpr` on a function is not advisory to the extent that being able to use its return value as a template argument “requires” compile-time evaluation (*i.e.*, except for an interpreter). – Davis Herring Oct 17 '20 at 02:28
  • @DavisHerring Yes, thank you, I added a (very brief) tweak to my answer. – Paul Sanders Aug 20 '22 at 09:31