Liste des Groupes | Revenir à cl c |
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".
Les messages affichés proviennent d'usenet.