Variable Scope

Learn how variables can have local or global scope depending on where they are declared.

We'll cover the following

We have seen before how the area of the program where a variable can be accessed is called the scope of that variable. Here, we revisit the concept of scope after having introduced functions.

Local vs global scope

Any variable declared inside a function is local to that function, and is not accessible outside the function. Similarly, code within a function doesn’t have access to variables that have been declared outside of that function (for example in another function, or in the main function). If you want this functionality, then you can specify that a variable be global.

Any variable declared outside of any function (it also has to be outside of main) is said to have a global scope, and can be seen by every function. In C, global variables are known as external variables (they are external to any function).

Example

In the following code, the variable myGlob is declared outside of the main function and outside of the myFunc function and thus can be accessed by code within both. On the other hand, the variable myInt is declared within the myFunc function and is thus local to myFunc and cannot be accessed outside of myFunc (for example from within main). Similarly, the variable myChar is declared within main and so cannot be seen within myFunc.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy