Liste des Groupes | Revenir à cl c |
On 23/05/2024 09:17, David Brown wrote:Clearer code, better checking along the way, better typing. I don't think constexpr lets you do things you couldn't do before, but it lets you do those things in a neater way. (IMHO.)If I try to be precise about the terms "constant expression", "integer constant expression", etc., I suspect I will get the details wrong unless I spend a lot of time checking carefully. So I hope it is good enough for me to be a bit lazy and quote the error messages from gcc (with "-std=c23 -Wpedantic").We can write:
>
>
With this code, compilation fails "initialiser element is not a constant" for y.
>
int x = 100;
int y = x / 20;
int zs[y];
>
>
With this code, compilation fails because the zs is actually a VLA, and "variably modified 'zs' at file scope" is not allowed.
>
const int x = 100;
const int y = x / 20;
int zs[y];
>
>
This code, however, is fine:
>
constexpr int x = 100;
constexpr int y = x / 20;
int zs[y];
>
>
This also works, even for older standards:
>
enum { x = 100 };
enum { y = x / 20 };
int zs[y];
>
>
But constexpr works for other types, not just "int" which is the type of all enumeration constants. (And "enum" constants are a somewhat weird way to get this effect - "constexpr" looks neater.)
>
And in general, I like to be able to say, to the compiler and to people reading the code, "this thing is really fixed and constant, and stop compiling if you think I am wrong" rather than just "I promise I won't change this thing - or if I do, I don't mind the nasal daemons".
#define X 100
#define Y ((X) / 20)
int zs[Y];
I cannot see a good justification for constexpr.
I already see bad usages of constexpr in C++ code. It was used in cases where we know for sure that is NOT compile time. This just make review harder "why did someone put this here?" conclusion was it was totally unnecessary and ignored by the compiler. The programmer was trying to add something extra, like "magic" hoping for something that would never happen.IME poor or confusing uses of "constexpr" are for functions, not objects, and C23 does not support "constexpr" for functions.
Les messages affichés proviennent d'usenet.