Why is it allowed to declare an automatic array with size depending on user input? [duplicate]

假如想象 提交于 2019-12-08 15:55:21

问题


I'm using MinGW to compile for C++11 and I found out that this doesn't throw an error:

int S;
cin>>S;
char array[S];

While this does ("storage size of 'array' isn't known"):

char array[];

To me, the size is also unknown in the first case, as it depends on what the user input is.

As far as I knew, automatic arrays are allocated at compile time in stack memory. So why wouldn't the first example fail?


回答1:


You are apparently not aware of the GNU GCC extension Arrays of Variable Length. Therefore your first code compiles.

The error message is something different. You have to specify the array length.

gcc has the -pedantic switch - enabling this switch the compiler will report your first code as invalid:

warning: ISO C++ forbids variable length array ‘array’

Read also this thread What is the purpose of using -pedantic in GCC/G++ compiler?

Use very carefully compiler extensions because should you port your code to another compiler then you are in big trouble.




回答2:


It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language.




回答3:


[This answers the original version of the question which asked about a static array; Deduplicator corrected this misconception, but now the question is missing a part.]

If your assumption that this piece of code defined a static array were correct, you'd be wondering for a good reason indeed: Something that is determined at compile time, like data with static storage duration, can obviously not depend on user input at run time. This truism is independent of any specific language.

The array defined in your code snippet has, by contrast, automatic storage duration, vulgo is created on the stack. A complete minimal working example would have made the case clearer: It would have shown that the code is in a function.

Objects with automatic storage duration can be created as needed at run time; there is no logical problem preventing that, which should fix your general headache ;-).

But note that, as some programmer dude correctly remarked, standard C++ nevertheless does not permit the definition of arrays whose size is not known at compile time; standard C does though, since C99. The rationale for C++ no following that amendment is that C++ provides better means for the use case, like the vector template. gcc, which is the compiler used in MinGW, permits this as an extension (and why not — it's available in the compiler anyway).



来源:https://stackoverflow.com/questions/52077767/why-is-it-allowed-to-declare-an-automatic-array-with-size-depending-on-user-inpu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!