The Wayback Machine - https://web.archive.org/web/20240917003936/https://www.geeksforgeeks.org/scope-rules-in-c/
Open In App

Scope rules in C

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The scope of a variable in C is the block or the region in the program where a variable is declared, defined, and used. Outside this region, we cannot access the variable and it is treated as an undeclared identifier.

  • The scope is the area under which a variable is visible.
  • The scope of an identifier is the part of the program where the identifier may directly be accessible.
  • We can only refer to a variable in its scope.
  • In C, all identifiers are lexically(or statically) scoped.

Example

C
// C program to illustrate the scope of a variable
#include <stdio.h>

int main()
{
    // Scope of this variable is within main() function
    // only.
    int var = 34;

    printf("%d", var);
    return 0;
}

// function where we try to access the var defined in main()
void func() { printf("%d", var); }


Output

solution.c: In function 'func':
solution.c:15:28: error: 'var' undeclared (first use in this function)
 void func() { printf("%d", var); }

Here, we tried to access variable names var As we can see that if we try to refer to the variable outside its scope, we get the above error.

Types of Scope Rules in C

C scope rules can be covered under the following two categories:

  1. Global Scope
  2. Local Scope

Let’s discuss each scope rule with examples.

1. Global Scope in C

The global scope refers to the region outside any block or function.

  • The variables declared in the global scope are called global variables.
  • Global variables are visible in every part of the program.
  • Global is also called File Scope as the scope of an identifier starts at the beginning of the file and ends at the end of the file.

Example

C
// C program to illustrate the global scope
#include <stdio.h>
 
// variable declared in global scope
int global = 5;
 
// global variable accessed from
// within a function
void display()
{
    printf("%d\n", global);
}
 
// main function
int main()
{
    printf("Before change within main: ");
    display();
 
    // changing value of global
    // variable from main function
    printf("After change within main: ");
    global = 10;
    display();
}

Output
Before change within main: 5
After change within main: 10

Linkage of Variables in Global Scope

Global variables have external linkage by default. It means that the variables declared in the global scope can be accessed in another C source file. We have to use the extern keyword for that purpose.

Example of External Linkage

file1.c

C
// filename: file1.c
#include <stdio.h>

// Define the global variable
int a;

// Define the function to use the global variable
void myfun()
{
    printf("%d\n", a);
}


main.c

C
// filename: main.c
#include <stdio.h>

// Declare the external variable and function
extern int a;
void myfun();

int main(void)
{
    // Initialize the global variable
    a = 2;

    // Call the function to print the value of 'a'
    myfun();

    return 0;
}


Output

2

Note: To restrict access to the current file only, global variables can be marked as static.

2. Local Scope in C

The local scope refers to the region inside a block or a function. It is the space enclosed between the { } braces.

  • The variables declared within the local scope are called local variables.
  • Local variables are visible in the block they are declared in and other blocks nested inside that block.
  • Local scope is also called Block scope.
  • Local variables have internal linkage.

Example

C
// C program to illustrate the local scope
#include <stdio.h>

// Driver Code
int main()
{
    {
        int x = 10, y = 20;
        {
            // The outer block contains
            // declaration of x and
            // y, so following statement
            // is valid and prints
            // 10 and 20
            printf("x = %d, y = %d\n", x, y);
            {
                // y is declared again,
                // so outer block y is
                // not accessible in this block
                int y = 40;

                // Changes the outer block
                // variable x to 11
                x++;

                // Changes this block's
                // variable y to 41
                y++;

                printf("x = %d, y = %d\n", x, y);
            }

            // This statement accesses
            // only outer block's
            // variables
            printf("x = %d, y = %d\n", x, y);
        }
    }
    return 0;
}

Output
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20

FAQs on Scope Rules in C

Q1. What if the inner block itself has one variable with the same name? 

Answer:

If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the point of the declaration by inner block.

Q2. What is the difference between the scope and lifetime?

Answer:

The scope and lifetime of a variable are often confused with one another 

  • The scope of the variable is the region where it is valid to refer to the variable using its name.
     
  • The lifetime of the variable is the time between it is allocated memory and it is deleted from the memory.

Q2. What about functions and parameters passed to functions? 

Answer:

A function itself is a block. Parameters and other local variables of a function follow the same block scope rules.

Q3. Can variables of the block be accessed in another subsequent block?

Answer:

No, a variable declared in a block can only be accessed inside the block and all inner blocks of this block.

Example: Accessing variable in outer blocks

C
int main()
{
  {
      int x = 10;
  }
  {
      // Error: x is not accessible here
      printf("%d", x);  
  }
  return 0;
}


Error

prog.c: In function 'main':
prog.c:8:15: error: 'x' undeclared (first use in this function)
  printf("%d", x); // Error: x is not accessible here
               ^
prog.c:8:15: note: each undeclared identifier is 
reported only once for each function it appears in

Example: Accessing variables in inner block

C
// C program to illustrate scope of variables

#include<stdio.h>

int main()
{
    // Initialization of local variables
    int x = 1, y = 2, z = 3;

    printf("x = %d, y = %d, z = %d\n",
    x, y, z);
    {

        // changing the variables x & y
        int x = 10;
        float y = 20;
        
        printf("x = %d, y = %f, z = %d\n",
        x, y, z);
        {

            // changing z
            int z = 100;
            printf("x = %d, y = %f, z = %d\n",
            x, y, z);
        }
    }
    return 0;
}

Output
x = 1, y = 2, z = 3
x = 10, y = 20.000000, z = 3
x = 10, y = 20.000000, z = 100




Previous Article
Next Article

Similar Reads

C | Variable Declaration and Scope | Question 1
Consider the following two C lines int var1; extern int var2; Which of the following statements is correct (A) Both statements only declare variables, don't define them. (B) First statement declares and defines var1, but second statement only declares var2 (C) Both statements declare define variables var1 and var2 Answer: (B) Explanation: See Under
1 min read
C | Variable Declaration and Scope | Question 2
Predict the output #include &lt;stdio.h&gt; int var = 20; int main() { int var = var; printf(&quot;%d &quot;, var); return 0; } (A) Garbage Value (B) 20 (C) Compiler Error Answer: (A) Explanation: First var is declared, then value is assigned to it. As soon as var is declared as a local variable, it hides the global variable var.Quiz of this Questi
1 min read
C | Variable Declaration and Scope | Question 3
#include &lt;stdio.h&gt; extern int var; int main() { var = 10; printf(&quot;%d &quot;, var); return 0; } (A) Compiler Error: var is not defined (B) 20 (C) 0 Answer: (A) Explanation: var is only declared and not defined (no memory allocated for it) Refer: Understanding “extern” keyword in CQuiz of this Question
1 min read
C | Variable Declaration and Scope | Question 4
#include &lt;stdio.h&gt; extern int var = 0; int main() { var = 10; printf(&quot;%d &quot;, var); return 0; } (A) 10 (B) Compiler Error: var is not defined (C) 0 Answer: (A) Explanation: If a variable is only declared and an initializer is also provided with that declaration, then the memory for that variable will be allocated i.e. that variable wi
1 min read
C | Variable Declaration and Scope | Question 5
Output? int main() { { int var = 10; } { printf(&quot;%d&quot;, var); } return 0; } (A) 10 (B) Compiler Error (C) Garbage Value Answer: (B) Explanation: x is not accessible. The curly brackets define a block of scope. Anything declared between curly brackets goes out of scope after the closing bracket.Quiz of this Question
1 min read
C | Variable Declaration and Scope | Question 6
Output? #include &lt;stdio.h&gt; int main() { int x = 1, y = 2, z = 3; printf(&quot; x = %d, y = %d, z = %d \n&quot;, x, y, z); { int x = 10; float y = 20; printf(&quot; x = %d, y = %f, z = %d \n&quot;, x, y, z); { int z = 100; printf(&quot; x = %d, y = %f, z = %d \n&quot;, x, y, z); } } return 0; } (A) x = 1, y = 2, z = 3 x = 10, y = 20.000000, z
1 min read
C | Variable Declaration and Scope | Question 7
int main() { int x = 032; printf(&quot;%d&quot;, x); return 0; } (A) 32 (B) 0 (C) 26 (D) 50 Answer: (C) Explanation: When a constant value starts with 0, it is considered as octal number. Therefore the value of x is 3*8 + 2 = 26Quiz of this Question
1 min read
C | Variable Declaration and Scope | Question 8
Consider the following C program, which variable has the longest scope? int a; int main() { int b; // .. // .. } int c; (A) a (B) b (C) c (D) All have same scope Answer: (A) Explanation: a is accessible everywhere. b is limited to main() c is accessible only after its declaration.Quiz of this Question
1 min read
Scope Resolution Operator vs this pointer in C++
Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name. Consider below C++ program: C/C++ Code // C++ program to show that local parameters hide // class members #include &lt;iostream&gt; using namespace std; class Test { int a; public: Te
3 min read
Structure Sorting (By Multiple Rules) in C++
Prerequisite : Structures in CName and marks in different subjects (physics, chemistry and maths) are given for all students. The task is to compute total marks and ranks of all students. And finally display all students sorted by rank. Rank of student is computed using below rules. If total marks are different, then students with higher marks gets
4 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 50 C Coding Interview Questions and Answers (2024)
C is the most popular programming language developed by Dennis Ritchie at the Bell Laboratories in 1972 to develop the UNIX operating systems. It is a general-purpose and procedural programming language. It is faster than the languages like Java and Python. C is the most used language in top companies such as LinkedIn, Microsoft, Opera, Meta, and N
15+ min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library &lt;stdio.h&gt; and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read