Variable Declaration in C


Introduction to Variable Declaration in C

Variables are the most essential part of any programming language.

Let's say we need to calculate the area of a rectangle. To make this arithmetic calculation, we need to store the length and width of the rectangle. To store the length and width of the rectangle, we need to allocate some space in a memory location for the data, and the name given to that memory location is called Variable.

For each different data, we give different variable names to it for later use in the program.

For a better understanding, let's look at the following image. It shows the memory location where the data is stored with a variable named as myvar and value 22 to it.

 

General syntax for declaring a variable

In variable declarations, we can declare variables in two ways:

Declaration of variable without initializing any value to it

data_type variable_name;

Eg:- char Final_Grade; // Final_Grade is a variable of type char, and no value is assigned to it.

Declaration of variable with initializing some value to it

data_type variable_name = val;

Eg:- int age = 22; // age is a variable of type int and holds the value 22.

Here, data_type specifies the type of variable like int, char, etc.

variable_name specifies the name of the variable. val is the value for which we are initializing the variable.


Rules to Declare Variable in C

In C language, we need to declare a variable with suitable data type and variable name.

Here are some of the rules we need to follow while declaring a variable in C:

Variables should not be declared with the same name in the same scope.

A variable name can start with anything like the alphabet and underscore. But the variable name should not start with a number.

A variable name must not be a reserved keyword in C. For example, if you declare a variable name as label, int, float, char, function, else etc., then it will not be able to be used as a variable name.

A variable name can contain any combination of alphabets, numbers and underscores.

All the declaration statements must end with a semi-colon. (;)

It is suggested to declare the variables of same data type in the same line.

It will be better if we declare variable names with some meaningful names and then it clearly describes the purpose of the variable.

 

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.