×

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end of this article, you will have a better understanding about what scope and lifetime are, and how to use them in C. We will also provide some examples to help illustrate these concepts and provide you with a better understanding.

What is Scope in C?   

Scope in C is the part of a program where a variable is accessible. It is the region of a program where a variable can be encountered and used.

There are three types of scope in C:

1. Global Scope

Global scope in C language refers to the accessibility of a variable or function throughout the entire program, rather than just within a specific function or block of code.

For example, consider the following C code:

Example:

#include <stdio.h>
int global_var = 5; // global variable
void function1() 
{
    printf("Global variable value in function1: %d\n", global_var);
}
int main() 
{
    printf("Global variable value in main: %d\n", global_var);
    function1();
    return 0;
}

The output of this program would be:

Output:

Global variable value in main: 5
Global variable value in function1: 5

In this code, the variable "global_var" is declared outside of the function, making it a global variable. This means that it can be accessed and used within any function in the program, including "function1" and "main".

As you can see, the value of the global variable "global_var" is the same in both "main" and "function1", demonstrating that it is accessible throughout the entire program.

Global scope in C language is also known as file scope because it is accessible to all the functions and other code defined in the same file. These variables are defined outside of any function, which makes them global in scope. The main advantage of using global variables is that they can be accessed and modified by any function in the program, allowing for more flexibility and ease of use. However, it is important to note that using global variables can lead to potential bugs and difficulties in debugging, especially when multiple functions are modifying the same variable.

Another important aspect of global scope in C is that these variables are initialized to zero or null by default, unless they are explicitly given a value. This means it can be used without having to initialize them before use.

2. Function Scope

Function scope in C language refers to the accessibility of a variable or function within a specific function or block of code.

For example, consider the following C code:

Example:

#include <stdio.h>
void function1() 
{
    int local_var = 10; // local variable
    printf("Local variable value in function1: %d\n", local_var);
}
int main() 
{
    function1();
    printf("Local variable value in main: %d\n", local_var); // error, local_var is not defined in main
    return 0;
}

The output of this program would be:

Output:

Local variable value in function1: 10

In this code, the variable "local_var" is declared within the function "function1", making it a local variable. This means that it can only be accessed and used within the scope of that specific function.

Here, the following error message will appear in the main function:

error: 'local_var' undeclared (first use in this function)

As you can see, the value of the local variable "local_var" is only accessible and defined within the function "function1" and it is not accessible in the main function. This is an example of function scope in C language.

Function scope variables are very useful for avoiding conflicts with global variables. They also help in avoiding bugs and making the code more readable, maintainable and less error-prone.

Another important aspect of function scope in C is that these variables are not initialized by default, unlike global variables. This means that they need to be explicitly initialized before use. This is important to remember when working with local variables as it helps to avoid undefined behavior.

In addition to variables, function scope also applies to functions themselves. Functions defined within other functions are only accessible within the scope of the outer function and are not visible to the rest of the program. This allows for encapsulation and prevents naming conflicts with other functions in the program.

3. Block Scope

Block scope in C language refers to the accessibility of a variable or function within a specific block of code, such as within a loop or conditional statement.

For example, consider the following C code:

Example:

#include <stdio.h>
int main() 
{
    int i;
    for (i = 0; i < 5; i++) 
{
        int block_var = i; // block scope variable
        printf("Block variable value in loop: %d\n", block_var);
 }
printf("Block variable value after loop: %d\n", block_var); // error, block_var is not defined outside of the loop
return 0;  
}

The output of this program would be:

Block variable value in loop: 0
Block variable value in loop: 1
Block variable value in loop: 2
Block variable value in loop: 3
Block variable value in loop: 4

In this code, the variable "block_var" is declared within the ‘for” loop, making it a block scope variable. This means that it can only be accessed and used within the scope of that specific block of code, in this case, the “for” loop.

Here, the following error message will appear after the loop:

error: 'block_var' undeclared (first use in this function)

As you can see, the value of the block scope variable "block_var" is only accessible and defined within the scope of the “for” loop and it is not accessible outside of it.

Block scope variables are very useful in situations where you want to avoid conflicts with global and function-scope variables, or when you want to limit the scope of a variable to a specific block of code. They also help in avoiding bugs and making the code more readable, maintainable and less error-prone.

It's important to note that block scope variables are not only limited to loops, but also apply to conditional statements and other types of blocks, such as if-else, switch-case, and others.

What do you mean by Lifetime in C?

The lifetime of a variable refers to the period of time during which the variable is allocated memory and can be accessed.

The lifetime of a variable can be divided into three categories: static, automatic, and dynamic.

1. Static: A variable with a static lifetime is allocated memory at compile time and remains in memory until the end of the program. This means that the memory for a static variable is allocated in the data segment, and is available for use throughout the entire execution of the program.

For example:

static int x = 10;

In this example, the variable x is allocated memory at compile time and has a static lifetime. It can be accessed and used throughout the entire program.

2. Automatic: Automatic variables are allocated memory on the stack and their lifetime is limited to the block in which they are declared. This means that the memory for an automatic variable is allocated on the stack when the block is entered, and is deallocated when the block is exited.

For example:

void func() 
{
   int x = 10;
   // x can be used here
} 
// x is deallocated when the block is exited

In this example, the variable x is allocated memory on the stack when the function func() is called, and is deallocated when the function exits.

3. Dynamic: Dynamic variables are allocated memory on the heap, and their lifetime is not limited to a specific block. Memory for dynamic variables is allocated using the malloc() or calloc() functions, and deallocated using the free() function.

For example:

int *ptr = (int *)malloc(sizeof(int));
*ptr = 10;
// use ptr
free(ptr);

In this example, the variable ptr is allocated memory on the heap using the malloc() function, and its lifetime is not limited to a specific block. It can be accessed and used throughout the entire program, until it is deallocated using the free() function.

It's important to note that if an automatic variable goes out of scope, its memory is freed and can be reused by other variables. If a pointer to an automatic variable is not freed, it leads to a memory leak or other errors if not used correctly.

Comparison between Scope and Lifetime

In C, variables have a variety of scopes and lifetimes depending on where and how they are declared, and also on how the variables are defined.

Variable TypeScopeLifetime
Local variableLimited to the function or block where it is declaredExists as long as the function or block is executing
Global variableAvailable throughout the entire programExists for the duration of the program
Static variableLimited to the function or block where it is declaredRetains its value between function calls

In order to understand the difference between scope and lifetime, there are a few more C variables that need to be considered.  

  • The ‘extern’ variable is used to access a global variable defined in another compilation unit. The ‘extern’ keyword is used to declare a variable in a source file, but the variable itself is defined in another source file. The scope of an extern variable is the entire program, but the lifetime is the same as the global variable it references.
  • The ‘register’ variable can be defined within a function, indicating that variable should be stored in a CPU register. The scope and lifetime of a register variable is the same as a local variable, but it is stored in a register instead of memory. This could improve performance by reducing the memory access time. However, the number of registers available is limited, so the use of register variables should be used with care and only when they are likely to improve performance.
  • The ‘const’ variable, which is used to declare a variable that cannot be modified after it is initialized. The scope and lifetime of a ‘const’ variable is the same as a regular variable, but the value cannot be changed. ‘const’ variables are typically used to define constants or to protect variables from accidental modification.
  • ‘_Thread_local’ variable, introduced in the C99 standard, is a thread-local storage (TLS) variable that only has a single instance for each thread. This means that each thread has its own copy of the variable and can only access its own copy. This can be useful for multithreaded programming as it allows for the safe sharing of data between threads.

Conclusion:

In conclusion, C provides several options for variable declaration and each of them have different characteristics in terms of scope and lifetime which can affect the program behavior and performance. It's important to use the correct variable type for your specific use case to ensure that your program works as intended and efficiently.


Related Topics

Banker’s Algorithm in C

Introduction Before doing a "s-state" check to look for potential activities and deciding if allocation should be allowed to continue, the banker's algorithm, a resource allocation and deadlock avoidance algorithm, tests...

5 minutes read.

memcmp() in C

Introduction: In this article we are discuss about memcmp() function in C. This function permits the person to evaluate the bytes of the two characters, as mentioned above. Depending on...

4 minutes read.

Calloc in C

The calloc() is a library function in C which is used for memory allocation. The calloc() function dynamically allocates multiple blocks of memory to complex data structures. This includes data structures...

3 minutes read.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

Nested if-else statement in C

If we use an if-else statement within another if statement in a C program, it is called a nested if-else statement in C. It helps to check the condition inside...

3 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

#define in C

#define in C In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the...

3 minutes read.

Bank management system in C

This is a mini project that is constructed completely using the C language. The bank management system is a beginner friendly project. To construct this user only needs to know...

12 minutes read.

For loop in C Programming

In the C programming language, the for loop is used to repeatedly iterate over a set of instructions or a section of code. It is frequently used to traverse array-based...

3 minutes read.

Const vs Volatile in C

Introduction Qualifiers are nothing but keywords which are used to modify the properties of a variable. Const and Volatile keywords are qualifiers in C. The Const qualifier is applied to the...

4 minutes read.

Pointer to pointer in C

A pointer to another pointer is another type of multiple indirections and a chain of many pointers. Generally, a pointer consists of the address of the variable. Once a pointer to...

4 minutes read.

Return array from function in C

Return array from function in C C programming does not require the return to a function of a whole array as an argument. However, you can return a pointer to an array without...

2 minutes read.

C Program Swap Numbers in cyclic order Using Call by Reference

The three integers that the user entered in cyclical sequence are swapped in this tutorial using call by reference. C Program: #include <stdio.h> void cyclic_Swap ( int *X, int *Y, int *Z ); int...

2 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Use of fflush(stdin) in C

Use of fflush(stdin) in C Usually, fflush() is only used for the output stream. The purpose is to clean (or flush) the output buffer and transfer the buffered data into...

2 minutes read.

memmove() in C

Introduction: In this article we are discuss about the memmove() function in C. This function transfers memory blocks from one location to another. The memmove() function is declared in the...

3 minutes read.

Loop Questions in C

Question 1: What is For loop syntax? Ans: The syntax that has been used for the ‘for’ loop in C programming language is: for (initialization statement /*for providing a value to variables*/; test...

19 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Flow Chart of Do while loop in C

This is a flowchart that represents the process of executing the Do while loop in the C programming language Generally, as we know there are three main components of Do While...

3 minutes read.

Simple Programs in C Language

In this article, we will discuss the basic programs in C language. Addition of two values in C. Swapping two values. Finding the odd or even values. Finding vowels and consonants in C. Finding the...

11 minutes read.