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.


Declaration of a Variable

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.


Definition of a Variable

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.

What if I just want to declare a variable?

To declare a variable without defining it, we can use the storage class called “extern.” We will discuss this in more detail later.


Initialization

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.


Important Points

  • A variable can only be defined once.
  • We can assign multiple values to a variable at different times, but initialization occurs when a value is assigned for the first time.


Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.