Variables are the data objects which are used to store a value. These values can be manipulated during the program execution.
We should declare the variable first before using it in our program.
How to declare a variable?
The Declaration of the variable specifies the name & type of the variable.
Syntax:
<Data Type> <variable_name>
;
- Eg1: int sum;
- Eg2: char alphabet;
Here ‘sum‘ is a variable name and ‘int‘ is a datatype that specifies that ‘sum’ can store only the values of type integer. We will see Datatypes in our upcoming sessions.
Defining a variable:
When we declare a variable, It contains some garbage value. Garbage value means an unexpected value (it might be zero also). So after the declaration, when we assign some value to the variable. It is known as the variable definition.
Syntax:
<Data_type> <variable_name>;
<Variable name> = <value>;
example:
- int a ;
- a = 10;
Now ‘a’ is defined with a value of 10.
Why do we get garbage value?
Consider, when we declare an integer variable, 4 bytes of memory will be allocated to it. If there were already 0’s in those 4 bytes then there will be no problem, else if the 4 bytes contain info that we have used earlier then it will be garbage. so we need to clear it. It can be done by initializing the variable with 0.
How to initialize a variable?
Defining a variable with a value at the time of declaration is known as initialization.
Declaration + Definition = Initialization;
Syntax: <Datatype> <variable_name> = <value>
Example: int a = 0;
Tip: It is always a good practice to initialize a variable with zero after declaration.
Note: Please refer to Page:35 i.e Chapter 2 – Section 2.1 “Variable Names” in the book “The C programming language 2nd edition” written by Brian Kernighan and Dennis M Ritchie.