Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

Variable Length Array (VLA) in C++ compilers

As we already know, VLA (standardized in C99) are not part of the standard in C++.

So the code below is "illegal" in C++:

void foo(int n) {
  int vla[n];
  for (int i = 0; i < n; ++i) {
    vla[i] = i;
  }
}

Despite of that the compiler (g++ and clang++) accepts the code as valid syntax, producing just a warning in case -pedantic flag is enable.

ISO C++ forbids variable length array ‘vla’ [-Wvla]

My questions are:

  • Why does the compiler accept that declaration?
    The compiler cannot just reject an array in which length [is-no-know-at-compile-time]?
    Is there a sort of compatibility syntax rule to follow?

  • What does the standard say about?
    From the assembly code produced I see the compiler writes in the stack in the loop, like a normal array, but I cannot find anything about the standard behaviour.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why does the compiler accept that declaration?

Because its authors chose to make it do so.

GCC in particular allows, by default, a lot of non-standard stuff that was historically accepted by old C compilers. They like "compatibility" in that sense.

What does the standard say about [it]?

Precisely what the warning states it says about it: ISO C++ forbids variable length arrays.

C++ does not have VLAs.

Where you see one being accepted, it is a compiler extension; to find out how that compiler implements such an extension, you would have to ask the compiler's authors (or examine its source, if applicable).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...