consteval vs constexpr on variables
Asked Answered
D

1

25

Is there any difference between constexpr and consteval ?

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

Is it better to use constexpr than consteval?

Delay answered 16/10, 2020 at 19:55 Comment(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.Godunov
K
43

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

Kindless answered 16/10, 2020 at 20:0 Comment(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).Edaedacious
Where can I find what you wrote above regarding the difference between constexpr and consteval in the C++20 standard ?Factorage
@belloc This is all it seems to have to say, strangely: eel.is/c++draft/dcl.constexpr#note-3 More digging might uncover a little more.Kindless
I have just found this paper P1073R3 by R. Smith, Andrew Sutton and Daveed Vandervoorde. Thank you for having answered my comment.Factorage
@belloc YW. Good sleuthing skills. Why can't the standard explain this properly anywhere? I had a bit more of a nose round but it doesn't seem to.Kindless

© 2022 - 2024 — McMap. All rights reserved.