C Tutorial

C Tutorial C Language Environment Setup Execution flow of C program C printf and Scanf C Data type C Token Variable in C Operators in C Comments in C Escape Sequence in C C – Storage Classes C Decision control statement Loop Statement in C Break, continue and goto statement in C Type Casting in C Function in C Recursion in C String in C C Array Pointer in C Dynamic memory allocation C –Structure Nested Structure in C Union in C File Handling in C C pre-processor Static Function In C Sizeof In C Selection Sort In C Scope Of Variables In C Runtime Vs Compile Time In C Random Access Lseek In C Queue Implementation In C Pseudo Code In C Prototype In C Pointer To Pointer In C Pointer Arithmetic In C Passing Array To Function In C Null Character In C Merge Sort In C Macros In C Library Functions In C Memory Leak In C Int In C Goto And Labels In C Fibonacci Series In C Fflush In C Derived Data Types In C Data Types In C Const Vs Volatile In C Character Set In C Character Class Tests In C Calloc In C C Pointers Arrays In C Include In C Clrscr In C C Vs Java String Literals In C Types Of Pointers In C Variables In C Volatile In C Why C Is A Middle Level Language Infix To Postfix Program In C Ceil function in C LCM of two numbers in C Quick sort in C Static in C function pointer as argument in C Top Array Keywords in C Add two numbers using the function in C Armstrong program in C using function Array, Declaring Arrays and Array Initialization Limitations of Inline Function in C Merge and Merge sort with example in C Do-While Loop in C For Loop in C While-Loop in C Difference between while and do-while loop in C Array Of Structures in C Data Structures And Algorithms in C Types Of Structures In C How to Avoid Structure Padding in C Use of Structure in C Do WHILE LOOP in C Programming Examples For Loop in C Programming Examples Entry Control Loop in C Exit control loop in C Infinite loop in C Nested loop in C pow() function in C String Handling functions in C Prime Number code in C Factorial Program in C using For Loop Factorial Program in C Using While Loop Fibonacci Series in C Using For Loop Fibonacci series in C using while loop Prime Number Program in C using for Loop While Loop in C programming examples Built-in functions in C Assert() Function C vs Java Strings Call Back Function in Embedded C Else If Ladder fgets() function Ftell() Function getc() function getch() function gets() function Heap Sort Nested if-else statement Pi() Function Positioning of file Write() function abs() function in C Attributes in C C program to find factorial of a number using Recursion Ferror() in c fopen() function in C Fibonacci series program in C using Recursion Formatted Input and output function in C Snake Game in C User Defined Functions in C Beep() function in C Cbrt() function in C Hook() function in C Isalnum() function in C C Program to find the Roots of a Quadratic Equation C Switch Statements Difference between rand() and srand() function in C Difference between while and for loop in C Doubly Linked list in C Example of Iteration in C How to use atoi() function in C How to use floor() function in C How to use sine() function in C How to use Typedef Struct in C Integer Promotions in C C Program Swap Numbers in cyclic order Using Call by Reference C Program to Find Largest Number Using Dynamic Memory Allocation C Program to Find the Largest Number using Ternary Operator C/C++ Program to Find the Size of int, float, double and char Find the Largest Three Distinct Elements in an Array using C/C++ Loop Questions in C Modulus on Negative Numbers in C Multiplication table program in C using For loop Nested Loops in C Programming Examples C Program for Mean and Median of an Unsorted Array Results of Comparison Operations in C and C++ Reverse a Stack using Recursion in C Simple hash() function in C strcat() Function in C Sum of N numbers in C using For loop Use of free() function in C Write a program that produces different results in C and C++ C Function Argument and Return Values Keywords in C Bank management system in C Calendar application in C Floor() Function in C Free() Function in C How to delete a file in C How to move a text in C Remove an element from an array in C Unformatted input() and output() function in C What are linker and loader in C SJF Scheduling Program in C Socket Programming in C Structure in C Tower of Hanoi in C Union Program in C Variable Declaration in C What is Linked List in C While Loop Syntax in C fork() in C GCD program in C Branching Statements in C Comma Operator in C Control statement in C Double Specifier in C How to create a binary file in C Long int in C Palindrome Number in C Pure Virtual Function in C Run Time Polymorphism in C Types of Array in C Types of Function in C What is a buffer in C What is required in each C Program Associativity of Operators in C Bit Stuffing Program in C Actual and Formal Parameters Addition of two Numbers in C Advantages of function in C Arithmetic Progression Program in C Binomial Coefficient Program in C Difference between Array and List in C Diffie-Hellman Algorithm in C How to convert a number to words in C How to convert a string to hexadecimal in C Difference between If and Switch Statement in C C and C++ Binary Files C program that does not Suspend when Ctrl+Z is Pressed Different ways to Declare the Variable as Constant in C Range of Int in C C Program to find the size of a File FIFO Example in the C Language For loop in C Programming GCD program of two numbers in C GPA Calculator in C How to Calculate Time Complexity in C How to include graphics.h in C How to measure time taken by a function in C How to return a Pointer from a Function in C What is the main in C Addition of Matrix in C Booleans in C C Program for Extended Euclidean algorithms C Program of Fencing the Ground Ceil and Floor in C Compound Interest Program in C Displaying Array in C Distance Vector Routing Protocol Program in c Dos.h Header File in C Language DSA Program in C Explain the two-way selection in C Fee Management System in C File Operations in C Malloc function in C Multiplication Table in C Simple Programs in C Language tolower() Function in C Type Conversion in the C Why does sizeof(x++) not Increment x in C Advantages of Dynamic Memory Allocation in C Armstrong Number in C Assignment Operator Program in C Banker’s Algorithm in C Binary Search in C with Best and Worst Time Complexity Caesar Cipher Program in C Call by Value and Call by Reference in C Conditional Operator in C CRC Program in C Deadlock Detection Program in C Decimal to Binary in C Difference between If Else and Nested If Else in C Difference between Pre-increment and Post-increment in C Difference between Scope and Lifetime in C Evaluation of Arithmetic Expression in C Explain the Increment and Decrement Operators in C Fseek Function in C Functions in C How to Find Square Free Numbers in C Length of an Array Function in C OpenGL in C Projects on C language in 2023 Purpose of a Function Prototype in C Stdio.h in C Two-Dimensional array in C What is String Comparison in C

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.