Variables: For better understanding lets remember variable as any container.
Container is a device which holds things of different sizes .Similarly variable holds data of different sizes.To be clear on bits and byte used in storage of data see fig given above.General form of variable declaration is
type variable_list;
Variable are declared in following 3 places:
Local variables(inside functions)
Formal parameters(in the definition of function parameters)
Global variables(outside of all functions)
Local variables:
Variables that are declared inside a function are called local variables.Local variables can be used only by statements that are inside the block in which the variables are declared. Local variables are not known outside their own code block.A block of code begins with an opening curly brace and terminates with a closing curly brace Each time a function is called a place is allocated in stack for that function with a return value after function is executed.Hence variable declared inside function has local scope.
As you can see in example a stack is allocated to function 'sum' when its called from main. Variables used in sum i.e x,y,z is placed in stack of sum.After execution , z value is stored in location allocated for return value in stack.Hence z is returned and stored in c of stack allocated for function main. This why local variables cant be accessed from other functions.
Formal parameters:
If a function has input parameters/arguments, it must declare variables that will accept the values of the arguments. These variables are called the formal parameters of that function. They behave local variables inside the function.
Eg: In example given below 'a' is formal parameter of function hello
void hello(char a)
{
int b=0;
while(b> 5)
{
b-- ;
printf("%c",a);
}
}
Note:Since formal parameters are like local variables, they are also dynamic and are destroyed upon exit from the function.
Global variables:
Global variables can be used by any piece of code.They will hold their value throughout the program's execution. You create global variables by declaring them outside of any function. Any expression can access them, regardless of its position in main program.
Eg: 'b' is a global variable
#include<stdio.h>
int b=0;
main()
{
while(b> 5)
{
b-- ;
printf("%d",b);
}
}
0 comments:
Post a Comment