This C code should fail, but it works. Why is this?

People, I think I will throw away all my humble knowledge of C. Look at this code:

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 cause an error for two reasons: firstly, I declare Num and Vetor after executing the command (srand), and second, because I declare Vetor based on Num, it should not be right? because these array sizes should not be decided at runtime, but at compile time right?

I am really surprised that his work, and if you guys could explain why I can use such things as that would be great.

This is the use of GCC.

+4
source share
2 answers

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

From Wikipedia :

Several new features have appeared in C99, many of which have already been implemented as extensions in several compilers:

  • built-in functions
  • mixed declarations and code, variable declaration is no longer limited by the scope of the file or by running a compound statement (block)
  • several new data types, including long long int, optional extended integer types, an explicit boolean data type, and complex type, represent complex numbers
  • variable length arrays
  • support for single-line comments starting with //, as in BCPL or C ++
  • new library features like snprintf
  • etc. ( more details )
+16
source

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

+1
source

All Articles