0
0
C++programming~5 mins

Scope of variables in C++

Choose your learning style9 modes available
Introduction

Scope of variables tells us where a variable can be used in the code. It helps keep things organized and avoids confusion.

When you want to use a variable only inside a small part of your program, like inside a function.
When you want to share a variable across many parts of your program, like global settings.
When you want to avoid accidentally changing a variable outside its intended area.
When you want to understand why a variable is not accessible in some part of your code.
When debugging to check if a variable is visible where you expect it to be.
Syntax
C++
/* Variable declared inside a function - local scope */
void example() {
    int x = 5; // x is local to example()
}

/* Variable declared outside functions - global scope */
int y = 10; // y is global

int main() {
    // y can be used here
    return 0;
}

Variables declared inside functions or blocks have local scope.

Variables declared outside all functions have global scope and can be used anywhere after declaration.

Examples
This shows a variable 'a' that only exists inside the function 'func'.
C++
void func() {
    int a = 3; // 'a' is local to func
    // 'a' cannot be used outside func
}
This shows a global variable 'b' that can be used anywhere in the program after its declaration.
C++
int b = 7; // global variable

int main() {
    // 'b' can be used here
    return 0;
}
This example shows how a local variable can hide a global variable with the same name inside a function.
C++
int x = 1; // global

void f() {
    int x = 2; // local to f, hides global x
    // inside f, 'x' is 2
}

int main() {
    // here 'x' is 1
    return 0;
}
Sample Program

This program shows a global variable and a local variable inside a function. The local variable is only visible inside the function, but the global variable is visible everywhere.

C++
#include <iostream>

int globalVar = 100; // global variable

void show() {
    int localVar = 50; // local variable
    std::cout << "Inside show(): localVar = " << localVar << "\n";
    std::cout << "Inside show(): globalVar = " << globalVar << "\n";
}

int main() {
    show();
    // std::cout << localVar; // This would cause an error because localVar is not visible here
    std::cout << "Inside main(): globalVar = " << globalVar << "\n";
    return 0;
}
OutputSuccess
Important Notes

Local variables are created when the function/block starts and destroyed when it ends.

Global variables exist for the whole program run but use them carefully to avoid confusion.

Variables with the same name in different scopes do not interfere with each other.

Summary

Scope defines where a variable can be used in the program.

Local variables live inside functions or blocks only.

Global variables can be used anywhere after they are declared.