DEV Community

제민욱
제민욱

Posted on

Global vs Static in C++

Key Differences

Aspect Global Variable Static Variable
Scope Accessible throughout program Limited to file, function, or class scope
Visibility Shared across files (extern) Restricted to declaring scope
Lifetime Entire program duration Entire program duration

Example Code

Global Variable

// globals.cpp
int globalVar = 42; // Global variable

// main.cpp
#include <iostream>
extern int globalVar; // Declaration for the global variable from another file

void modifyGlobal() {
    globalVar++; // Accessible across files
}

int main() {
    modifyGlobal();
    std::cout << "Global Variable: " << globalVar << std::endl; // Prints: 43
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

File-Scope Static Variable

#include <iostream>

static int staticVar = 10; // File-scope static

void modifyStatic() {
    staticVar++; // Accessible only within this file
}

int main() {
    modifyStatic();
    std::cout << "Static Variable: " << staticVar << std::endl; // Prints: 11
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Function-Scope Static Variable

#include <iostream>

void counter() {
    static int count = 0; // Retains value across calls
    count++;
    std::cout << "Count: " << count << std::endl;
}

int main() {
    counter(); // Prints: 1
    counter(); // Prints: 2
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)