Google News
logo
Variables in C language
A variable is a name of memory location. It is used to store data. Changed the variables value keeps changing during the execution of the program and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.

The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

Rules for naming variables :

• First letter must be an alphabet.
• Only alphabets, digits and underscore are allowed in variable names.
• We cannot use any other symbols like comma, hyphen, and period….etc.
• Spaces are strictly not allowed.
• Should not be a keyword like if, else, while…etc.
• The variable name cannot contain a maximum length of 32 characters.

Let's see the syntax to declare a variable :
<data type> variable-list;
The example of declaring variable is given below :
int a;
float f;

Here a, f are variables and int, float are data types.

We can also provide values while declaring the variables as given below :

int a=10, b=20; // this is called declaration, not an assignment.

float f;

f=15.5; //this is not an initialization, it is called assignment.

The Programming language C has two main variable types

1. Local Variables

2. Global Variables

Local Variables

Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.

When a local variable is defined, it is not initialized by the system, you must initialize it yourself.

When execution of the block starts the variable is available, and when the block ends the variable 'dies'. It must be declared at the start of the block.

  Example :
void function1()
{  
int x=10; //local variable  
}  
Global Variables

Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.

Global variables are initialized automatically by the system when you define them.

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.

  Example :
int value=20; //global variable  
void function1()
{  
int x=10; //local variable  
}