Declaration, Definition, and Initialization of a Variable
In this lesson, we will learn about the concepts of declaration, definition, and initialization of a variable in the C programming language.
In this lesson, we will learn about the concepts of declaration, definition, and initialization of a variable in the C programming language.
When we declare a variable, we are letting the compiler know that the variable exists in our program. We provide the name and type of the variable to the compiler. However, the compiler does not allocate memory for the variable at this stage.
When we define a variable, we assign memory to it. The compiler allocates memory based on the variable’s type.
Note that in modern C compilers, declaration and definition are often done together in a single step. So, when we write the variable’s data type and name together, we are both declaring and defining the variable simultaneously.
For example, when we write “int var;”, the compiler understands that we are declaring and defining a variable named “var” of type “int.” The compiler also allocates 4 bytes of memory for this variable, assuming that the size of an integer is 4 bytes.
To declare a variable without defining it, we can use the storage class called “extern.” We will discuss this in more detail later.
Initialization occurs when we assign a value to a variable for the first time.
For example:
int var; //var is declared and defined.
var = 10; //var is initialized.
In the second line of the above example, we initialize the variable “var” with the value 10. It’s important to note that we are referring to the same variable “var” that was defined in the first line. A variable can only be defined once. That’s why we don’t need to include the “int” keyword before the variable name in the second line, as it would be redefining the same variable, which is not allowed in C.
Leave a comment