在C ++书中,数组绑定必须是常量表达式,但为什么下面的代码工作? [英] In C++ books, array bound must be constant expression, but why the following code works?
本文介绍了在C ++书中,数组绑定必须是常量表达式,但为什么下面的代码工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include< iostream>
using namespace std;
int main(){
int n = 10;
int a [n];
for(int i = 0; i a [i] = i + 1;
cout<< a [i]<< endl;
}
return 0;
}
在Mac下的Xcode4中工作正常
$ b $ b >解决方案
这个aa C99功能叫做 VLA ,一些编译器也允许在C ++中。它是堆栈上的分配,就像在 int a [10]
。
#include <iostream>
using namespace std;
int main(){
int n=10;
int a[n];
for (int i=0; i<n; i++) {
a[i]=i+1;
cout<<a[i]<<endl;
}
return 0;
}
worked fine in Xcode4 under Mac
as said in books, it should be wrong, why?
so confused~
解决方案
This a a C99 feature called VLA which some compilers also allow in C++. It's allocation on stack, just as it would be with int a[10]
.
这篇关于在C ++书中,数组绑定必须是常量表达式,但为什么下面的代码工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文