Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of size defined by not constant variable

Tags:

c++

arrays

There is such code:

#include <iostream>

int main()
{
  int size;
  std::cin >> size;

  size = size + 1;
  int tab3[size];

  tab3[0] = 5;
  std::cout << tab3[0] << " " << sizeof(tab3) << std::endl;
  return 0;
}

The result is:

$ g++ prog.cpp -o prog -Wall -W 
$ ./prog
5
5 24

Why does this code even compile? Shouldn't be length of array a constant variable?

I used g++ version 4.4.5.

like image 831
scdmb Avatar asked Nov 14 '11 17:11

scdmb


1 Answers

Variable-length arrays in C++ are available as an extension in GCC. Compiling with all warnings should have alerted you to that fact (include -pedantic).

like image 164
Kerrek SB Avatar answered Nov 09 '22 23:11

Kerrek SB