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++?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With