C++静态数组和sizeof运算符

Ash*_*hot 0 c++ arrays static sizeof

我所知道的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)
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 5

首先,代码不是有效的C++,因为C++中没有可变长度数组(VLA).它们是C功能.您的C++编译器支持它们作为非标准扩展.使用-Wvla-pedantic获取警告:

warning: ISO C++ forbids variable length array 'array' [-Wvla]
Run Code Online (Sandbox Code Playgroud)

其次,sizeof()当应用于C VLA时,运算符不再是编译时构造.C标准在§6.5.3.4中sizeof暗示了这一点:运营商:

如果操作数的类型是可变长度数组类型,则计算操作数; 否则,不评估操作数,结果是整数常量.