【发布时间】:2022-01-14 19:52:52
【问题描述】:
在 C11(及更高版本)中,整数常量表达式只能具有以下操作数:
作为类型转换的直接操作数的浮动常量
以下代码:
int a[ A > B ? 16 : 32 ];
当A 和B 是浮动常量时在C 中无效:
$ echo '#include "t576.h"' | clang -std=c11 -pedantic -Wall -Wextra -DA=1.0 -DB=2.0 -c -xc -
In file included from <stdin>:1:
./t576.h:1:5: warning: size of static array must be an integer constant expression [-Wpedantic]
但在 C++ 中有效:
$ echo '#include "t576.h"' | clang++ -std=c++11 -pedantic -Wall -Wextra -DA=1.0 -DB=2.0 -c -xc++ -
<nothing>
此要求的起源/基本原理是什么?
额外问题:在未来的 C 标准修订版中删除此要求是否有用?
【问题讨论】:
-
浮点值
A或B是“强制转换的直接操作数”吗?不会的。 -
您究竟是如何定义 A 和 B 的?我在 C11 中将其测试为
const float A = 0.6f; const float B = 0.65f; int a[ A > B ? 16 : 32 ];,它的行为符合预期。 -
@martorad:在 C 语言中,const 限定符不会神奇地将变量更改为编译时常量。只有
#define可用于定义符号常量。换句话说,您正在定义一个 VLA... -
@SergeBallesta,确实,那是我的错。也就是说,使用
#define初始化 A 和 B 也适用于 C11。不过,就像您提到的那样,在不知道 OP 的定义的情况下,我们只能猜测。 -
@LanguageLawyer 这归结为浮点常量还是变量?
标签: c floating-point language-lawyer c11 constant-expression