Join Regular Classroom : Visit ClassroomTech

Programming in C++ – codewindow.in

C++ Programing

#include 

// Global variable with static storage class (internal linkage)
static int globalVar = 10;

// Function with static local variable
void foo() {
    static int localVar = 0; // This variable retains its value between calls.
    localVar++;
    std::cout << "LocalVar: " << localVar << std::endl;
}

int main() {
    auto int a = 5; // 'auto' storage class (optional, same as 'int a = 5;')

    register int b = 10; // 'register' storage class (compiler may ignore it)

    extern int externVar; // Declaration of an external variable (defined elsewhere)
    std::cout << "ExternVar: " << externVar << std::endl;

    for (int i = 0; i < 5; i++) {
        foo(); // Call the function to see the behavior of static local variable.
    }

    return 0;
}

Keep in mind that the usage of register is rarely seen in modern C++ codebases due to advanced compiler optimizations. The auto storage class is rarely used explicitly since it is the default behavior for local variables. The most common storage class you will encounter and use in C++ is static.

#include 

int main() {
    auto int x = 42; // 'auto' is optional here (same as 'int x = 42;')
    std::cout << x << std::endl;

    return 0;
}
  1. Global variables (outside functions): The default storage class for global variables declared outside any function is extern. If you declare a variable at the global scope without explicitly specifying any storage class, it is assumed to be an extern variable.

Example of a global variable with the extern storage class:

#include 

int globalVar = 10; // 'extern' is optional here (same as 'extern int globalVar = 10;')

int main() {
    std::cout << globalVar << std::endl;

    return 0;
}

It’s worth noting that the use of auto as a storage class for local variables is rarely seen in modern C++ since it is the default behavior. For local variables, you can simply declare them without any storage class specifier, and the compiler will treat them as auto variables. For global variables, you can declare them without any storage class specifier, and they will be extern by default.

#include 

int main() {
auto int x = 42; // 'auto' is optional here (same as 'int x = 42;')
std::cout << x << std::endl;

return 0;
}

In this example, x is a local variable with the default “auto” storage class.

      

Go through our study material. Your Job is awaiting.

Recent Posts
Categories