Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ 不支持变量长度数组,请不要误导新人 #4

Closed
Guyutongxue opened this issue Feb 28, 2022 · 1 comment
Closed

C++ 不支持变量长度数组,请不要误导新人 #4

Guyutongxue opened this issue Feb 28, 2022 · 1 comment

Comments

@Guyutongxue
Copy link

您好。偶然看到您的这一仓库,发现您的 C++数组长度可以为变量吗? 文章中提出了错误的观点。我在这里郑重地告知您:C++ 不支持变量长度数组(VLA)

简单来说,VLA 是 C 语言的语法,于 1999 年在 C99 标准中引入(并在 2011 年的 C11 中又取消)。但 C++ 直至目前不支持任何 VLA 相关语法。容易引起误会的是,GCC 和 Clang++ 编译器提供了包含 VLA 的GNU 扩展语法,并且默认引入这些扩展。因此,VLA 在这些 C++ 编译器下可行。反之,如果关闭这些扩展(通过添加 -pedantic-errors 选项)或者非 GNU 兼容的编译器(如 MSVC),则 VLA 不可用。

实例测试

GCC 在严格模式下禁止 C++ VLA
Clang++ 在严格模式下禁止 C++ VLA
MSVC 在任何情形下都不允许 C++ VLA

标准文本

In a declaration T D where D has the form

D1 [ constant-expression opt ] attribute-specifier-seq opt

and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, the type of the declarator-id in D is “derived-declarator-type-list array of N T”. The constant-expression shall be a converted constant expression of type std​::​size_­t ([expr.const]). Its value N specifies the array bound, i.e., the number of elements in the array; N shall be greater than zero.

取自 C++ 最新标准草案 [dcl.array] 第一段

其中,注意加粗的文本:(上述语法形式方括号内的)constant-expression 需要是一个经转换后类型为 std::size_t常量表达式

@chengxumiaodaren
Copy link
Owner

chengxumiaodaren commented Feb 28, 2022

嗯好的,谢谢你的issue。
标准是不支持的,这是属于GCC的扩展,公众号文章不能修改,我其他平台的文章应该有提到。
已修正链接。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants