tags:

views:

65

answers:

2

Why this dont work:

int size = 2;
int array[size];

int main() {
  return 0;
}

It says the error: array bound is not an integer constant

And this work:

int size = 2;

int main() {
  int array[size];
  return 0;
}

Anyone knows the reason??' thanks

+1  A: 

Dynamic sized arrays is a feature of C99 and is not included in the current C++ standard at all.

If you are compiling as C++ neither should work. If you change to a const variable then both methods will be allowed by the C++ standard.

Brian R. Bondy
no, if I compile with g++ or gcc and name it .cpp I get the same problem, why!
Daniel G. R.
+7  A: 

In C++ or C89/90 neither works. These languages require that array size is an Integral Constant Expression (ICE). In your examples size is not an ICE. If your C++ or C89/90 compiler allows it, it is nothing else than a non-standard compiler extension.

In C99 the second works because this is how Variable Array Length (VLA) specification is defined. VLA can only be defined in local scope.

AndreyT
+1 didn't know about VLA local scope only. nice.
Brian R. Bondy
Remember that VLA are allocated on the stack. While its fine for small datasets, its not a substitute for heap allocation.
Yann Ramin