Local vs Global Variables

Local Variables:

Example:

void display() {
    int localVar = 10;  // Local variable
    cout << "Local Variable: " << localVar << endl;
}

int main() {
    display();
    // cout << localVar;  // Error: localVar is not accessible here
    return 0;
}

Global Variables:

Example:

int globalVar = 20;  // Global variable

void display() {
    cout << "Global Variable: " << globalVar << endl;
}

int main() {
    display();
    globalVar += 5;  // Modifying global variable
    cout << "Modified Global Variable: " << globalVar << endl;
    return 0;
}

Memory Layout of a Program

A C++ program's memory layout consists of several segments:

Code Segment: Contains the compiled machine code of the program

Data Segment: