2013-03-26 93 views
0

据我所知sizeof是编译时运算符,那么为什么此代码无需任何警告就能正确编译和运行?C++静态数组和sizeof运算符

#include <iostream> 

    int main() {  
     int size; 
     std::cin >> size; 
     int array[size]; 
     std::cout << sizeof(array)/sizeof(int) << std::endl; 
    } 



g++ -v 
Reading specs from /usr/lib/gcc/x86_64-redhat-linux/3.4.6/specs 
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=x86_64-redhat-linux 
Thread model: posix 
gcc version 3.4.6 20060404 (Red Hat 3.4.6-9) 
+0

你对此有何评论? – 2013-03-26 10:19:35

+0

这段代码编译和运行是否完美?你正在使用哪种编译器? – Subhajit 2013-03-26 10:19:44

+0

可能重复[在C/C++中sizeof()的机制是什么?](http://stackoverflow.com/questions/1581839/whats-the-mechanism-of-sizeof-in-cc) – GSerg 2013-03-26 10:19:47

回答

5

首先,代码是无效的C++,因为没有variable-length arrays(VLAS)在C++中。他们是一个C功能。你的C++编译器支持它们作为非标准的扩展。使用-Wvla-pedantic得到一个警告:

warning: ISO C++ forbids variable length array 'array' [-Wvla] 

其次,当应用到C沃拉斯的sizeof()运营商不再是一个编译时间结构。在在此C标准提示§6.5.3.4的sizeof操作者

如果操作数的类型是可变长度数组 类型,操作数被评估;否则,操作数不会被评估,结果是一个整数常量 。