Why is the data type necessary for the initialization that follows the declaration?

Consider a simple C program:

int a; // declaration int a = 11; // initialization int main(int argc, char* argv[]) { int b; // declaration b = 10; // assignment 

If the initialization a was written without a data type, for example a = 11 , the compiler generates a warning. Why does the initialization of a require a data type when the declaration of a already indicates its data type?

+7
c
source share
3 answers

int a in the file area is a โ€œpreliminaryโ€ definition (since it does not have the initialization part). This means that a can again be defined with a value at a later point.

A preliminary determination may or may not act as a definition, depending on whether there is an actual external definition before or after it in the translation unit:

 int a = 5; // defines a in the current translation unit with external linkage and a value of 5 int a; // tentative definition with no effect (a is already defined) 

Another method, as a rule, has more practical advantages:

 int a; ... int a = 5; 

A preliminary determination may precede the actual determination if, for example, the constant used for initialization is not available at the first point.

Edit:

It seems you are confused that you cannot perform the assignment in the file area. Program C is only allowed to have actual operations inside functions. Only files, types, and functions can be defined or declared in the file area.

+3
source share

I think this is due to the fact that you cannot write instructions in a global area. It means:

 int a = 11; 

Defines a variable. This tells the compiler to assign a static address to the variable because it is global. The default value (assignment) is just an added bonus. Taking into account that:

 a = 11; 

Is an instruction that is illegal.

+2
source share

as an example:

 int a; // <--- is a declaration int a = 11; // <--- is reference to a const value 

you can write code as follows: int a;

 int main() { a = 11; // <--- simply no warning. return 0; } 

This is because a = 1; // <--- is the code instruction int a = 1; // <--- is the ref value for const

In c, you cannot write an assignment from a scope.

-3
source share

All Articles