Scope of Variables within Functions in C

In this tutorial, we will focus on understanding the scope of variables within functions.


Introduction

accessible only within the main() function. No other function can directly access that variable. Also, it will be destroyed after the completion of the function. So, the lifetime of a variable is until the main() function completes its execution. Consider the following example:

#include <stdio.h>

void fun(void) {
    printf("%d", x);
}

int main() {
    int x = 10;
    fun();
    return 0;
}

Output:

Error. Undeclared identifier x.

Explanation:

The variable x is accessible only within the main() function as it is declared within the main() function. No other function can access it directly. We tried doing the same in the above function, but unfortunately we got an error 😕

The concept of scope of a variable plays an important role in understanding how variables are accessed and managed within functions. After understanding this concept through this tutorial, you can easily spot the area of visibility of a variable. Not only this, you can tell how long a variable will survive. You will obtain all these superpowers by the end of the tutorial, so let’s dive in.


Local Scope

Variables with local scope are called local variables. They are defined within a function or a block and due to this reason, the area of visibility is within the function or a block in which they are defined, and they survive until the function or a block completes its execution. 

  • Visibility:  within the function or a block. 
  • Lifetime:  till the function or a block completes its execution. 

Consider the following code:

#include <stdio.h>

void fun(void) {
    int x = 10;
    printf("%d", x);
}

int main() {
    fun();
    return 0;
}

Output:

10

Explanation:

The variable x is defined within the function fun(), so it is local to fun(). This means the variable x’s is accessible only within the fun() function and it will be destroyed after the execution of the function is done.


Global Scope

Variables defined in the global scope are called global variables. They are typically defined outside any function and at the top of the program (after the header files declaration and function prototypes). 

  • Visibility:  accessible to all the functions of the program.
  • Lifetime:  exist for the entire duration of the program’s execution. 

Consider the following code to better understand this concept:

#include <stdio.h>

int globalVar = 10;

void fun(void) {
    globalVar *= 10;
}

int main() {
    fun();
    printf("%d", globalVar);
    return 0;
}

Output:

100

Explanation:

globalVar is the global variable defined in the above program. We are accessing the variable within the fun() and the main() function. This clearly shows that the globalVar is accessible throughout the program. The function fun() is updating the globalVar making it equal to 100. Then, within the main() function, the value of the globalVar is displayed using the printf() function. 

There are a few considerations to keep in mind before declaring and using these variables:

  • Global variables are accessible to all the functions and hence, can be modified by any. This may lead to potential bugs which are difficult to spot. So, try to avoid declaring these variables whenever possible until it is super necessary for your application to work. 
  • Global variables cause “name conflicts” as they may conflict with the local variables of the functions. Out of local and global variables, local variables always win and hence, if the programmer wants to update the global variable, they may not be able to do so if the variable with the same name is declared within the function. So, be careful.

Static Variables

Static variables can either be local or global, but they retain their values either within the function calls or the entire file depending on where they are defined. 

  • Static local variables: retain their values within function calls. 
  • Static global variables: retain their values throughout the program but are not accessible outside the program file in which they are defined. 

Consider the following example of static local variable:

#include <stdio.h>

void fun(void) {
    static var = 5;
    var++;
    printf("%d ", var);
}

int main() {
    fun();
    fun();
    fun();
    return 0;
}

Output:

6 7 8

Explanation:

The variable var is declared as static within the function fun() and hence, it has the capability to retain its value. As it is defined with the function fun(), it’s visibility is within this function only. If we try to access it within the main() function, we would not be able to do so. 

Now, consider the following example of static global variable:

#include <stdio.h>

static var = 5;

void fun(void) {
    var++;
}

int main() {
    fun();
    fun();
    fun();
    printf("%d", var);
    return 0;
}

Output:

8

Explanation:

The variable is a global static variable, hence it can retain its value and it is visible throughout the program. This is the reason why both the main() and fun() functions can access it and make changes to it.


Function Parameters

Function parameters are a special type of local variables which are declared within a function and receive values from the arguments of the caller.

  • Visibility:  within the function in which they are declared. 
  • Lifetime: exists only for the duration of the function call.  

Consider the following example:

#include <stdio.h>

void fun(int x) {
    printf("%d", x);
}

int main() {
    int x = 20;
    fun(x);
    return 0;
}

Output:

20

Explanation:

Variable x is declared as a parameter within the function fun() and receives value 20 from the caller within the main() function.


Check Your Understanding

Question 1

What is the scope of a variable defined within a function?

Local
Global
Static
No scope
explanation

A variable declared within a function is called the local variable and it is visible only within the function. So, the scope of a local variable is local.

Question 2

What happens if the function parameter has the same name as the global variable?

The global variable is used within the function.
The function parameter shadows the global variable within the function.
It causes compilation error.
It causes runtime error.
explanation

If a function parameter has naming conflict with the global variable, then the function parameter always wins. Within the function where it is defined, it takes preference over the global variable. 

Always remember, local variables are always considered over global ones whenever naming conflicts arise.

Question 3

In which scenario using a global variable is beneficial over local variables?

When you need to save some memory.
When a variable needs to be retained within function calls.
When a variable needs to be accessed and modified by multiple functions.
None of the above.
explanation

Global variables are accessible throughout the program. Hence, they are useful when the requirement is to access and modify these variables in multiple functions.

Question 4

How does a static global variable differ from a regular global variable?

Static global variables do not retain their value between function calls, whereas regular global variables do.
Static global variables are accessible only within the file they are declared in, while regular global variables can be accessed from other files using the ‘extern’ keyword.
Static global variables consume a lot of memory compared to regular global variables.
None of the above.
explanation

Whenever a regular global variable is declared, it is accessible within the file (or a program) in which it is declared. On the other hand, static global variables are accessible to the other files apart from the file in which they are declared. By using the extern keyword, one can access these variables in different files within the same project.

Question 5

What will be the output of the following program?

#include <stdio.h>

int x = 10;

void fun() {
    int x = 30;
    printf("%d ", x);
}

int main() {
    printf("%d ", x);
    fun();
    printf("%d", x);
    return 0;
}
10 10 10
10 10 30
10 30 30
10 30 10
explanation

Let’s understand how the above code is printing the result 10 30 10:
– In the first printf() function, variable x is referring to the global variable x containing value 10. As there is no declaration of variable x within the main() function, the compiler will look for the global declaration of x.
– Then, the fun() is called, and there the local variable x is defined (note that it is the new definition. The global variable x is not modified; instead, a new local variable with the same name is defined within the function fun()). This variable gets preference over the global variable x within the fun() function and hence its value is displayed which is 30. 
– Finally, in the main() function the value of the global variable x is displayed once again, and therefore the final output is 10 30 10.

Your score is out of


Conclusion

Scope of a variable depends upon the area where the variable is defined. If a variable is defined within a function or a block, its visibility is within that function or the block and the variable is called the local variable. If it is defined outside all the functions and at the top of the program, then the variable is accessible throughout the program and it is called the global variable. Apart from this, in this tutorial we learned how putting static in front of a variable can change its behavior. Also, at last we discussed function parameters which are special types of local variables.



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.