[C]变长数组

变长数组在C99及C11的标准中支持,严格讲在C++的所有标准中都不支持变长数组,只是各家编译器对语言的扩展

//t.c
#include<stdio.h>

int foo(int n){
	int x[n];
	printf("%lu\n",sizeof(x));
	return n;
}

int main()
{
	foo(10);
	foo(20);
	return 0;
}

严格按照C99标准编译: clang t.c -o t -std=c99 -pedantic,输出正常

严格按照C11标准编译: clang t.c -o t -std=c11 -pedantic,输出正常

严格按照C89标准编译: clang t.c -o t -std=c99 -pedantic,提示如下的警告信息:

t.c:4:7: warning: variable length arrays are a C99 feature [-Wvla-extension]
        int x[n];
             ^
1 warning generated.

//t.cpp
#include<stdio.h>

int foo(int n){
	int x[n];
	printf("%lu\n",sizeof(x));
	return n;
}

int main()
{
	foo(10);
	foo(20);
	return 0;
}

严格按照C++98标准:clang t.cpp -o t -std=c++98 -pedantic,提示警告信息如下:

t.cpp:4:7: warning: variable length arrays are a C99 feature [-Wvla-extension]
        int x[n];
             ^
1 warning generated.

严格按照C++11标准:clang t.cpp -o t -std=c++11 -pedantic,提示警告信息如下:

t.cpp:4:7: warning: variable length arrays are a C99 feature [-Wvla-extension]
        int x[n];
             ^
1 warning generated.

猜你喜欢

转载自blog.csdn.net/adream307/article/details/82880994