Day#17 'C' Coding Challenge

Day#17 'C' Coding Challenge

What is the output of the following program?

#include <stdio.h> int var1 = 100; void main() { char a[10] = "TalentEve"; int var1 = 260; printf("%d",var1); }

-----------------------------------------

The above program tests two scenarios:

1. What is the scope of local variable?
2. What is the scope of global variable?
3. Priority of local vs global variable

-----------------------------------------

In the above program, var1 is declared twice. One within the main() function and one outside the function.
The var1 declared within the main() function (int var1 = 260;) is called local variable. The scope of this variable is only within main() function and it cannot be accessible outside the function. Even the value is not retained once the function is exited. However, storage class like static can be used to retain the value of the variable.
The var1 declared outside all functions and in a  (int var1 = 100;) is called global variable. The scope of this variable is entire file and it can be accessible anywhere in that function. Using storage class like global the variable can be accessed outside the file as well.

However, when it comes to local vs global, within a function local variable has priority. So, in main() function, when var1 is printed, it prints 260 and not 100.

Post a Comment

0 Comments