我看到一些像这样的代码:
int foo() { int sz = call_other_func(); char array[sz]; /* whatever */ }
我很困惑这将如何工作,甚至用gcc编译.数组的大小应该是静态的并在编译时确定,不是吗?
解决方法
这是有效的C99功能,称为
variable length arrays(VLA),如果使用gcc -std = c90 -pedantic进行编译,您将收到以下警告:
warning: ISO C90 forbids variable length array ‘array’ [-Wvla]
使用-std = c99 -pedantic不会产生警告,虽然gcc和clang都支持V95在C99模式之外,而且在C中也不允许VLA作为extension.
我们可以从C99 draft standard节中看到6.7.5.2阵列声明者第4段说(强调我的):
If the size is not present,the array type is an incomplete type. If the size is * instead of being an expression,the array type is a variable length array type of unspecified size,which can only be used in declarations with function prototype scope;124) such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size,the array type is not a variable length array type; otherwise,the array type is a variable length array type.