How are variables scoped in C



Here we will see how the C variables are scoped. The variables are always statically scoped in C. Binding of a variable, can be determined by the program text. These are independent of runtime function call stack.

Let us see one example to get the idea.

Example

# include <stdio.h> int x = 0; int my_function() {    return x; } int my_function2() {    int x = 1;    return my_function(); } int main(){    printf("The value is: %d\n", my_function2()); }

Output

The value is: 0

Here the result is 0. Because the value returned by my_function() is not depends on the function, which is calling this. This function always returns the value of the global variable x.

Updated on: 2019-07-30T22:30:25+05:30

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements