constexpr 常量

版本新特性 / C23

// *** 以前 ***
//在 C17 中,const 变量不是常量表达式,
//所以静态数组的大小或 case 标签需要宏或枚举常量
#define BUFFER_SIZE_OLD 16
enum { MAX_USERS_OLD = 100 };      //枚举常量始终是 int
static char bufferOld[BUFFER_SIZE_OLD];
//static const int n = 16; static char b[n];    <- error 在 C17 中

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

// *** 在 C23 版本中 ***
//constexpr:带类型的具名常量,在编译时计算
constexpr int bufferSize = 16;
constexpr double ratio = 0.5;      //枚举放不下 double
static char buffer[bufferSize];
size_t size = sizeof buffer;
//size is 16
//ratio is 0.5

//constexpr int seed = rand();    <- error: 值不是常量
//constexpr 只用于对象:C 没有 constexpr 函数
printf("size is %zu\n", size);
printf("ratio is %g\n", ratio);