Introduction
A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and it's type or class, before you actually try to do anything with it.
The Programming language C has Two main Variable Types as following:
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 initialised by the system, you must initialise it yourself. When execution of the block starts the variable is available and when the block ends the variable 'dies'.
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 initialised automatically by the system when you define them !
Every variable in C has it's own name. A variable without any name is not possible in C. Most important properties of variables name are it's unique names. The rules for writing variable name is same as that of identifiers.
Not two variables in C can have same name with same visibility.
For Example:
#include<stdio.h>
int main()
{
int a = 5; //Visibility is within main block
int a = 10; //Visibility is within main block
/* Two variables of same name */
printf("%d",a);
return 0;
}
Output: Compilation error
#include<stdio.h>
int a = 5; // Visibility is in whole program
int main()
{
int a = 10; //Visibility is within main block
/* Two variables of ame name */
printf("%d",a);
return 0;
}
Output: 10
But it is possible that two variable with same name but different visibility.
In this case variable name can access only that variable which is more local.
In C there is not any way to access global variable if any local variable is present of same name.
For Example:
#include<stdio.h>
int main()
{
int a=10; //Visibility within main block
{
a= a+5; //Accessing outer local variable 'a'
int a=20; //Visibility within inner block
a= a+10; //Accessing inner local variable 'a'
printf("%d",a); //Accessing inner local variable 'a'
}
printf("%d",a); //Accessing outer local variable 'a'
return 0;
}
Output: 30 15
0 comments:
Post a Comment