Variable Scope

Further increase your knowledge about function behavior in C by learning about variable scope inside and outside of a function.

Any variables declared inside a function, are local to that function, and are not accessible outside of 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 main()). 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 global, and can be seen by every function. In C, global variables are known as external variables (they are external to any function).

For example in the following code, the variable myGlob is declared outside of main() and outside of myFunc() and thus can be accessed by code within both. The variable myInt is declared within the function myFunc() and is thus local to myFunc() and cannot be accessed outside of myFunc() (for example 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