gcc 对 VLA 的 sizeof 运算符的评估是否不同?
g++
允许可变长度数组 (VLA) 作为扩展。 VLA 上的 sizeof
运算符的结果很有趣:
int main ()
{
char size = 20, a[10], b[size];
cout<<"sizeof(a) = "<<sizeof(a)<<endl; // sizeof(a) = 10, (can be used as template param)
cout<<"sizeof(b) = "<<sizeof(b)<<endl; // sizeof(b) = 20 !! (can't used be as template param)
}
在 sizeof(b)
的情况下,g++ 是否不遵循仅评估 sizeof
的标准在编译时? sizeof
是否超载?
g++
allows Variable Length Arrays (VLA) as an extension. The results of sizeof
operator on VLAs are interesting:
int main ()
{
char size = 20, a[10], b[size];
cout<<"sizeof(a) = "<<sizeof(a)<<endl; // sizeof(a) = 10, (can be used as template param)
cout<<"sizeof(b) = "<<sizeof(b)<<endl; // sizeof(b) = 20 !! (can't used be as template param)
}
In case of sizeof(b)
, is g++ not following the standard where sizeof
is evaluated only at compile time? Is sizeof
overloaded?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
VLA 是不计算
sizeof
操作数的规则的一个例外,如 C99, 6.5.3.4/2 中所指定:此行为是 g++ 扩展;在标准 C++(直至并包括 C++14)中,永远不会计算
sizeof
的操作数(并且不允许使用 VLA)。VLAs are an exception to the rule that the operand of
sizeof
is not evaluated, as specified in C99, 6.5.3.4/2:This behaviour is a g++ extension; in Standard C++ (up to and including C++14) the operand of
sizeof
is never evaluated (and VLAs are not permitted).VLA 在 C99 中引入。在 C99 中,sizeof(vla) 不是编译时常量,而是考虑数组的运行时大小。
gcc/g++
允许非 C99 代码中的 VLA 作为扩展。这样做时,编译器遵循 C99 语义。这就是你所观察到的。VLAs were introduced in C99. In C99,
sizeof(vla)
is not a compile-time constant, but takes into account the run-time size of the array.gcc/g++
allow VLAs in non-C99 code, as an extension. When doing so, the compilers follow the C99 semantics. This is what you're observing.变长数组是 C99 的一部分,C++ 中没有。 Gcc 允许它们作为 C++ 中的扩展,使用 C99 的行为,这确实表明
sizeof
返回数组的实际大小(因此在运行时评估)。 关于 sizeof 的维基百科文章对其行为进行了很好的总结。Variable Length Arrays are a part of C99, which is not in C++. Gcc allows them as an extension in C++ using the behaviour from C99, which does indeed say that
sizeof
returns the actual size of the array (and is therefore evaluated at runtime). The wikipedia article about sizeof gives a nice summary of its behaviour.