Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't C array initialization syntax allowed for arbitrary assignments?

Tags:

arrays

c

I was trying to learn the array fundamentals in Java and this question arises:

Version 1:

int[] x  = {12,34,56,78};

Version 2:

int[] x;  
x = {12,34,56,78};

Version 1 is correct but version 2 is incorrect.

Why is this the case? What is the story behind it?
Please, describe this from a compiler-oriented point of view.

like image 664
anirban karak Avatar asked Sep 25 '13 18:09

anirban karak


Video Answer


1 Answers

The compiler needs to know how much storage to allocate for the array when it is declared.

int x[] = {12,34,56,78};

In this case the compiler knows that it needs storage for four integers; this is comparable to saying int x[4].

int x[];
/* ... */
x = {12,34,56,78};

However, in this case the compiler sees int x[] and knows it must allocate space for an array but it doesn't know how much until it gets to the following line, at which time it is too late.

like image 141
maerics Avatar answered Oct 12 '22 21:10

maerics