Variables in c
Variable
When we want to store any information . we store it in address of the computer address is complex so we name it and naming of address known as variable.Variable declaration :- data_type variable_name;
Example: int x, y, z; char name;
Variable initialization :- data_type variable_name = value;
Example: int x = 50, y = 30;
There are Two types of Variables in c language.
- Local Variable.
- Global Variable.
Local Variable
- The scope of local variables will be within the function only.
- These variables are declared within the function and can’t be accessed outside the function.
- In the below example, m and n variables are having scope within the main function only. These are not visible to test function.
- Like wise, a and b variables are having scope within the test function only. These are not visible to main function.
For Example:-
#include<stdio.h>
void test();
int main()
{
int a = 20, b = 40;
// a,b are local variables of main function
//a and b variables are having scope
within this main function only.
printf("values : a = %d and b = %d", a, b);
test();
}
void test()
{
int x= 30, y = 50;
// x, y are local variables of test function
/x and y variables are having scope
within this test function only.
printf("values : x = %d and y = %d", x, y);
}
Output:-
values : a = 20 and b = 40
values : x = 30 and y = 50
Global Variable
- The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.
- This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions.
#include<stdio.h>
Void test();
int a = 20 , b = 40;
int x = 30 , y = 50;
int main()
{
printf("all variables are accessed from main function");
printf("values : a=%d:b=%d:x=%d:y=%d",a,b,x,y);
test();
}
void test()
{
printf("all variables are accessed from test function")
printf("values: a=%d:b=%d:x=%d:y=%d",a,b,x,y);
}
Output:- All variables are accessed from main function
values : a= 20 : b = 40 : x = 30 : y = 50
All variables are accessed from test function
values : a= 20 : b = 40 : x = 30 : y = 50
No comments: