Posted on 2008-08-13 16:56
小明 阅读(3606)
评论(18) 编辑 收藏 引用 所属分类:
C/C++
下面的C++代码能编译么?
#include <stdio.h>
#define NUM getnum()
int getnum()
{
int x = 0;
scanf("%d", &x);
printf("%d\n", x);
return x;
}
int main()
{
int array[NUM];
printf("array size =%d\n",sizeof(array));
return 0;
}
在g++中居然可以编译。
输入10,返回array size=40
输入20,返回array size=80
输入-1,返回array size =-4!!
问题:
1.这样的做法符合C++标准么?连sizeof成了运行期计算
2.这个array的空间应该分配在heap上,而不是stack上。g++做了什么手脚?
答案是:
1. C99的标准:
变长数组,不过支持大小为负数的数组就有些奇怪了
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C89 mode and in
c++. (However, GCC's implementation of variable-length arrays does not yet conform in detail to the ISO C99 standard.) These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited.
2. 其实是分配在stack上面,动态的调整esp就可以了