[英]define the length of an array with a variable in c++/c
I am reading a book saying that in C++ you can't do this: 我正在读一本书,说在C ++中您不能这样做:
int array_size = 3;
int array[array_size];
Then I tried it with gcc,but it didn't complain at all(exception warned about unused array
). 然后我用gcc尝试了一下,但是它一点也没有抱怨(异常警告了未使用的
array
)。
Also I read about this question .The 4th answer says that you can use something like this: char someCondition[ condition ];
我也读到了这个问题 。第四个答案说,您可以使用类似这样的东西:
char someCondition[ condition ];
To me the condition
would only be known until runtime,so the whole thing seems really confounding to me.Can anyone help explain this? 对我来说,
condition
只有在运行时才知道,所以整个事情对我来说真的很令人困惑。有人可以帮忙解释一下吗?
Thanks,G 谢谢,G
If You are using a C++ compiler it works because most of the C++ compilers provide a compiler extension that supports Variable Length arguments(VLA) . 如果您使用的是C ++编译器,则它会起作用,因为大多数C ++编译器都提供了支持Variable Length arguments(VLA)的编译器扩展。
If You are using a C compiler it works because the standard allows it. 如果您使用的是C编译器,则可以使用,因为标准允许它。
In C++, VLA are not allowed by the C++ Standard, so any usage of it through compiler extensions will make your code non portable. 在C ++中,C ++标准不允许VLA,因此通过编译器扩展对其进行任何使用将使您的代码不可移植。
C++ provides std::vector or std::array (C++11) which satisfy all the requirements using variable length array or c-style arrays resp and you should use them. C ++提供了std :: vector或std :: array (C ++ 11),它们使用可变长度数组或c样式数组分别满足所有要求,因此您应该使用它们。
Note that,since C99 standard, VLA's are allowed in C. 请注意,自C99标准以来,C中允许使用VLA。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.