Home > Backend Development > C++ > What\'s the Difference Between Static, Auto, Global, and Local Variables in C and C ?

What\'s the Difference Between Static, Auto, Global, and Local Variables in C and C ?

DDD
Release: 2024-11-02 17:34:02
Original
984 people have browsed it

What's the Difference Between Static, Auto, Global, and Local Variables in C and C  ?

Understanding Static, Auto, Global, and Local Variables in C and C

When working with variables in C and C , it's essential to grasp the nuances between static, auto, global, and local variables. This distinction pertains to both their accessibility and their lifespan in the program.

Local Variables

Local variables, sometimes referred to as "block-scope" variables, inhabit the code block in which they are declared. These variables only come into existence when the block is entered and cease to exist upon its exit. Illustrating this concept:

void f() {
    int i; // Local variable
    i = 1; // Accessible within f()
}
Copy after login

Global Variables

Global variables possess "file-scope" (in C) or "namespace-scope" (in C ). They can be accessed from any point of the program following their declaration, as shown here:

int i; // Global variable
void f() {
    i = 1; // Accessible anywhere
}
Copy after login

Automatic Variables

Automatic variables, known as "automatic storage duration" variables, reside locally. Their existence is confined to the duration of the block they inhabit. Upon exiting the block, these variables are destroyed and come into existence again when re-entering the block.

for (int i = 0; i < 5; ++i) {
    int n = 0; // Automatic variable
    printf("%d ", ++n); // Value of n is reset to 0 each iteration
}
Copy after login

Static Variables

Static variables, on the other hand, enjoy extended lifetimes within the program (referred to as "static storage duration"). Even when control exits their scope, their values live on.

for (int i = 0; i < 5; ++i) {
    static int n = 0; // Static variable
    printf("%d ", ++n); // Value of n persists across iterations
}
Copy after login

In conclusion, grasping the distinctions between these variable types allows for more efficient and targeted programming in C and C . Understanding their scope and lifespan enables developers to choose the appropriate variable type for their specific needs.

The above is the detailed content of What\'s the Difference Between Static, Auto, Global, and Local Variables in C and C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template