×

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

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Storage Class in C

C storage class is used to define the scope variables and function. There are four various types of storage classes that are given below. auto: The auto keyword is the default...

1 minute read.

How to move a text in C

A text can be moved to the desired location in the output based on the coordinates provided in the gotoxy() function. What is gotoxy() function? In C language, gotoxy() is a pre-defined...

3 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Macros in C

In the C programming language, the macro is defined as a segment of the code replaced by the macro defined value at the beginning. ‘#define’ is the directive that defines...

3 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 minutes read.

Difference between rand() and srand() function in C

What is the rand()? The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Prototype in C

A prototype is nothing but a model, a model of initial creation of an intended product. Similarly, in the C programming language, all functions have a prototype. In general, all...

4 minutes read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

String Handling functions in C

String :- The String is the collection of characters. Every String ends with the null character, and the String is enclosed in the double quotations .ie, "javaTpoint". If we see any...

5 minutes read.

C Pointers

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

4 minutes read.

While Loop Syntax in C

What is Loop? The statements in the sequence are repeatedly executed via looping statements in C until the condition is met. The body of a loop and a control statement make...

4 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.

Unformatted input() and output() function in C

Unformatted Input and Output functions take the character, character array, and strings as input. We can read-only character data types with these functions. These functions are already defined in the...

5 minutes read.

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.

Data Structures And Algorithms in C

C language is one of the most flexible and simple languages. So, it is always better to learn any concept in C language compared to other languages. Let us look...

13 minutes read.

Fibonacci series in C

We have learned about the Fibonacci series in mathematics. For a quick recap, A Fibonacci series is the sequence of numbers following a certain pattern i.e., the next number should...

3 minutes read.