Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining the size of array using variable

Tags:

c++

arrays

c

Is this valid in C language?

#include <stdio.h>
int main()
{
  int i = 5;
  int a[i];     // Compiler doesn't give error here. Why?
  printf("%d",sizeof(a));  //prints 5 * 4 =20. 4 is the size of integer datatype.
  return 0;
}

Compiler doesn't give error at the statement int a[i];. i isn't a constant then how can it compile successfully? Is it because I am using gcc compiler? Is it allowed in C++?

like image 364
user221458 Avatar asked Oct 02 '13 10:10

user221458


1 Answers

Yes, this is valid as of C99, and is called a variable-length array (VLA). In other words, it has been in an official language standard for around 14 years.

No, it's not valid in C++, see this question for details.

Also note that sizeof is not a function, so that can be written as printf("%zu\n", sizeof a); which also uses the proper format specifier for a size_t value.

like image 120
unwind Avatar answered Oct 11 '22 16:10

unwind