具有用户输入大小的 C++ 数组(也就是为什么要编译?)

C++ arrays with user input size (aka Why does this compile?)

我在 win 10 上使用 clang (10.0) 进行试验,代码片段如下:

#include <iostream>

using namespace std;

int main()
{
  const int N = 10;

  int ii;
  cout << "Enter value for ii: ";
  cin >> ii;

  int a[N+ii];

  for (int i = 0; i < N+ii; ++i) {
    a[i] = 0;
  }

  for (int i = 0; i < N+ii; ++i) {
    cout << "a[ " << i << "] = " << a[i] << endl;
  }

  return 0;
}

我不确定为什么没有编译错误(编译时不知道数组a的大小)????

PS:

  1. 两个 for 循环都是为了触发分段错误。
  2. 编译命令:clang.exe exp.cpp
  3. 我已经尝试 运行 ii 的代码,但它似乎工作正常 (ii = 10000, 100000, 1000000)

int a[N+ii];

这在 C++ 中是错误的。数组变量的大小必须是编译时常量。

I am not sure as to Why are there no compilation error (the size of the array a is unkown at compile time) ????

C++ 标准要求不能编译格式错误的程序。当编译器故意编译格式错误的程序时,您正在使用语言扩展。

该标准确实要求语言实现发出诊断消息,通知用户他们的程序格式错误。除非您在编译时提供 -pedantic 选项,否则 Clang 不符合标准。如果你确实使用它,这就是 clang 所说的:

warning: variable length arrays are a C99 feature [-Wvla-extension]

这就是 clang 文档对选项的描述:

-pedantic, --pedantic, -no-pedantic, --no-pedantic

Warn on language extensions