Consider the 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 of a
were written without the data type, such as a = 11
, the compiler raises a warning. Why does the initialization of a
require a data type, when the declaration of a
already specifies its data type?
All variables in the Java language must have a data type. A variable's type determines the values that the variable can have and the operations that can be performed on it. For example, the declaration int count declares that count is an integer ( int ).
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
Declare variables at first use. Rationale: It's best to declare variables when you first use them to ensure that they are always initialized to some valid value and that their intended use is always apparent.
Purpose. A type declaration statement specifies the type, length, and attributes of objects and functions. You can assign initial values to objects. A declaration type specification (declaration_type_spec) is used in a nonexecutable statement.
int a
at file scope is a "tentative" definition (because it lacks the initialising part). This means that a
can be defined again with a value at a later point.
A tentative definition 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)
The other way around usually has more practical merit:
int a;
...
int a = 5;
The tentative definition could precede the actual definition, if, for example, the constant used to initialise it is not available at the first point.
Edit:
You seem to be confused that you are not able perform an assignment at file scope. A C program is allowed to have actual operations only within functions. At file scope, one may only define or declare variables, types and functions.
I think this has something to do with the fact that you can't write instructions in the global scope. What it means is :
int a = 11;
Defines a variable. This tells the compiler to assign a static address to the variable, because it is global. The default (assignment) value is just an added bonus. Whereas :
a = 11;
Is an instruction, which is illegal.
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