Why is the C array initialization syntax not allowed for arbitrary assignments?

I tried to learn the basics of an array in Java, and the question is:

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 so? What is the story? Please describe this in terms of the compiler .

+6
source share
5 answers

The compiler must know how much memory is allocated for the array when it is declared.

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

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

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

However, in this case, the compiler sees int x[] and knows that it should allocate space for the array, but it does not know how much it will reach the next line, and at this time it is too late.

+3
source

In the latter case, the first line that the compiler should process is simply int x[]; . The compiler does not know how long it takes to make an array unless you give it the length int x[4]; or don’t give it initial values, which will determine the length.

+2
source

That's why

This is a variable declaration and initialization using array initialization syntax:

 int[] x = {12,34,56,78}; // this is java. my bad int x[] = {12,34,56,78}; // this is c 

This is the declaraction variable:

 int[] x; // java again int x[]; // this is c 

You are allowed to initialize a variable (which includes the use of array initialization syntax) when declaring a variable.

This is the assignment of a variable with a syntax error:

 x = {12,34,56,78}; 
+2
source

What looks like an assignment here is initialization. This syntax can only be used as part of a declaration, but not in a standalone expression.

Two parts of this syntax (to the left and to the right of the = sign) work together: the compiler infers the size of the array int x[] from the number of elements in the initializer; it cannot be added to type x at a later point, that is, at assignment, since the size of the C array must be known at the declaration point.

+1
source

Simple ... version 2 doesn't know how to allocate space for array values

+1
source

Source: https://habr.com/ru/post/954627/


All Articles