Global variables retains its value throughout the program.
Can be changed inside the functions and changes are retained outside the function ( or code block ).
#include <stdio.h>
int i=5;
int my_fun(){
printf("\n inside my_fun() i=%d",i); // 5 next cycle 6
i=i+1;
return 0;
}
int main(void){
printf("\n inside main() first i=%d",i); // 5
my_fun();
my_fun();
printf("\n inside main() last i=%d",i); // 7
return 0;
}
Output is here
inside main() first i=5
inside my_fun() i=5
inside my_fun() i=6
inside main() last i=7
Local variables
Local variables retains its value throughout the function or code block.
Values destroyed once the function execution completes.
Changes are not available outside the function as variable is not available to outside.
#include <stdio.h>
int i=5;
int my_fun(){
int i=10; // Add or remove static here
printf("\n inside my_fun() i=%d",i); // 10 second call 10
i=i+1;
return 0;
}
int main(void){
printf("\n inside main() first i=%d",i); // 5
my_fun();
my_fun();
printf("\n inside main() Last i=%d",i); // 5
return 0;
}
Output is here
inside main() first i=5
inside my_fun() i=10
inside my_fun() i=10
inside main() Last i=5
As the value of local variable is destroyed once the function execution is completed the value of i will all ways initialized to 10 and same will be displayed on each call to function.
By using static variable we can retain the value of the variable after the function call and reuse the same inside the function in subsequent call. So for first time inside the function i value will be displayed as 10 and next time it will display value as 11.
Static variables
Static variables retain its value though out the function or code block.
Values are NOT destroyed once the function execution completes. (Available for next function call )
Changes are not available outside the function as variable is not available to outside.
#include <stdio.h>
int my_fun(){
static int i=10; // Add or remove static here
printf("\n i=%d",i);
i=i+1;
return 0;
}
int main(void){
my_fun();
my_fun();
return 0;
}
Output is here
i=10
i=11
Practice Questions
Create a function to sum of all input numbers as they entered. This should display the sum including the just entered number. Exit the process if 0 is entered. Print command should be in main function . Hint : Use one static variable inside the function
In place of static variable use one local variable inside the function in above code and check the output.
Solution : functions()