Skip to main content

Scope of a variable in C

Scope of a variable in C

The scope of a variable in C refers to the region of the program where it can be accessed or used. The scope of a variable determines its visibility and lifetime in the program.

In C, there are majorly two types of scope:

Local scope (Local Variables)

Variables defined within a function have local scope, which means they are only accessible within that function. The lifetime of local variables begins when the function is called and ends when the function returns.

Global scope (Global Variables)

Variables defined outside of all functions have global scope, which means they can be accessed from anywhere in the program. The lifetime of global variables begins when the program starts and ends when the program terminates.

Apart from two primary type of scope, we also talk about additional scopes C:

File Scope

  • File scope variables are typically declared at the top of a source code file, outside of any blocks, such as functions or loops, and are visible throughout the source file.

  • They can be used by any function in the same source file

Block Scope

Block scope in C refers to the visibility of a variable within a block of code. For example, any variable defined within a function block, or if-else block will have a block scope.

Function scope

Function scope refers to the visibility of variables within a function. Variables with function scope are declared inside a function and are only visible within the scope of that function. They are also referred to as local variables.

Static Variables and Scope

Static variables are variables that retain their value between function calls. Static variables are declared using the static keyword and have a scope that is limited to the function in which they are declared.

Volatile Variables and Scope

  • A volatile variable is a variable whose value can be changed by an external agent, such as a hardware interrupt, without the knowledge of the program. The volatile keyword is used to declare a variable as volatile.

  • A volatile variable can be declared with either file scope, function scope, or block scope.