简体   繁体   中英

c++ variable size stack array in function that get const

I'm learning now C++ I'm reading the book Effective C++ (Scott Meyers). In the book, there is an item about const variables, and I try to work with them. I notice something very interesting that I what to know if it bug in C++: (I'm working with C++98 standard)

void Test(const int i)
{
    int arr[i] = {0};
    
    for (int j = 0; i > j; ++j)
    {
        arr[j] = i;
    }
}

This function will compile and work exactly as I want (create int array on the stack with the size of 'i'. When I remove the 'const' from 'i' it won't compile. I try this on gcc and clang.

Edit: link to Compiler Explorer

To catch this kind of mistake in the future the compiler flag you want for both g++ and clang++ is -pedantic . And always remember to specify your language standard or you don't know what you'll get.

$ g++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla
c++-vla.cpp: In function ‘void f(size_t)’:
c++-vla.cpp:3:30: warning: ISO C++ forbids variable length array ‘g’ [-Wvla]
    3 | void f(const size_t x) { int g[x]; }
      |                              ^

$ clang++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla
c++-vla.cpp:3:31: warning: variable length arrays are a C99 feature [-Wvla-extension]
void f(const size_t x) { int g[x]; }
                              ^
1 warning generated.

First of all, const in your function signature is ignored by the compiler. So the following two are equivalent:

Test(const int i) {}
Test(int i) {}

Secondly, this isn't valid C++ regardless of whether it compiles or not:

int arr[i] = {0};

It isn't valid because i is not a compile time constant ie, the value of i has to be known at the time of compilation.

Try on Compiler Explorer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM