当我运行以下代码时,它适用于C:
#include<stdio.h>
int main(void)
{
const int x=5;
char arr[x];
printf("%d",sizeof(arr));
}
Run Code Online (Sandbox Code Playgroud)
但是,不仅我之前读过const合格的变量不是real常量(这就是为什么它们不能在case条件下使用switch-case),但IBM的以下链接证实了(IBMLINK)并说:
const int k = 10;
int ary[k]; /* allowed in C++, not legal in C */
Run Code Online (Sandbox Code Playgroud)
为什么我允许const在C中使用合格变量作为数组大小而没有任何错误?
我很惊讶地发现可以在C++中为堆栈分配一个变长数组(例如int array[i];).它似乎在clang和gcc(在OS/X上)都能正常工作,但是MSVC 2012不允许它.
这个语言功能叫什么?它是官方的C++语言功能吗?如果是,那么哪个版本的C++?
完整示例:
#include <iostream>
using namespace std;
int sum(int *array, int length){
int s = 0;
for (int i=0;i<length;i++){
s+= array[i];
}
return s;
}
int func(int i){
int array[i]; // <-- This is the feature that I'm talking about
for (int j=0;j<i;j++){
array[j] = j;
}
return sum(array, i);
}
int main(int argc, const char * argv[])
{
cout << "Func 1 "<<func(1)<<endl;
cout << "Func 2 "<<func(2)<<endl;
cout << "Func 3 "<<func(3)<<endl;
return …Run Code Online (Sandbox Code Playgroud)