views:

128

answers:

2

Folks I think I will throw all my modest C lore away. Look at this code please:

int main( int argc, char ** argv, char ** envp )
{
int aa;

srand(time(NULL));

int Num=rand()%20;

int Vetor[Num];

for (aa=0; aa<Num; aa++)
  {
    Vetor[aa]=rand()%40;
    printf("Vetor [%d] = %d\n",aa,Vetor[aa]);
  }
}

I would think that this should throw an error for two reasons - first that I am declaring both Num and Vetor after executing a command (srand), second because I am declaring Vetor based on Num, this should not be possible right? because those array sizes should not be decided at runtime but at compile time right?

I am really surprised that his works and if you guys could point to some references why I can actually use stuff like this would be great. I think I lost some big changes to C in the last years...

oh by the way, this is using gcc

+9  A: 

These are C99 features, and it seems your compiler supports them. That's all ;)

From Wikipedia:

C99 introduced several new features, many of which had already been implemented as extensions in several compilers:

  • inline functions
  • intermingled declarations and code, variable declaration no longer restricted to file scope or the start of a compound statement (block)
  • several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers
  • variable-length arrays
  • support for one-line comments beginning with //, as in BCPL or C++
  • new library functions, such as snprintf
  • etc (more)
Samuel_xL
Oh! living and learning! better read the spec on C99, thanks for the answer
Andre Garzia
Yup, even `sizeof` must tell you the size of the variable-length array, so it is no longer just a compile-time thing, it must have a runtime implementation also.
dreamlax
+1  A: 

C99 supports declarations anywhere in the code, as well as VLAs. What compiler are you using?

Michael Foukarakis
thanks for the tip. This is GCC, just learned about C99 will catch up with the standards.
Andre Garzia