Константы constexpr

Изменения в новых версиях / C23

// *** before: ***
//C17: a const variable is not a constant expression, so the size of a
//static array or a case label needed a macro or an enum constant
#define BUFFER_SIZE_OLD 16
enum { MAX_USERS_OLD = 100 };      //an enum constant is always an int
static char bufferOld[BUFFER_SIZE_OLD];
//static const int n = 16; static char b[n];    <- error in C17

printf("sizeof bufferOld is %zu\n", sizeof bufferOld);

// *** in version C23: ***
//constexpr: a named constant with a type, computed while compiling
constexpr int bufferSize = 16;
constexpr double ratio = 0.5;      //an enum could not hold a double
static char buffer[bufferSize];
size_t size = sizeof buffer;
//size is 16
//ratio is 0.5

//constexpr int seed = rand();    <- error: the value is not a constant
//constexpr is for objects only: C has no constexpr functions
printf("size is %zu\n", size);
printf("ratio is %g\n", ratio);