Intermediate · C PROGRAMMING

Scope and local variables

What you will learn

Understand which variable a name refers to.

Understand the concept

A variable declared inside a block is visible from its declaration to the end of that block. An inner block may declare another variable with the same name; this hides the outer one within the inner block. Prefer clear names to avoid accidental shadowing.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

Inner: 2
Outer: 5

Practise

Rename the inner count to batch_count, then add the outer count to it.

Common mistake

A local variable does not remain accessible after its scope ends. Do not return a pointer to an automatic local variable.

Lesson discussion

Log in to participate.

#include <stdio.h>

int main(void) {
    int count = 5;
    {
        int count = 2;
        printf("Inner: %d\n", count);
    }
    printf("Outer: %d\n", count);
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
Inner: 2
Outer: 5
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA