What is the difference between a global variable and a global variable Static?

Asked

Viewed 102 times

7

What is the difference between a global variable and a static global variable? Example:

#include <stdio.h>

int numero = 5;
static int static_numero = 5;

int main(void)
{
    printf("numero: %d \n", numero);
    printf("static_numero: %d \n", static_numero);

    return 0;
}

Is there a difference between the two variables? If there is no difference then what would be the reason a global variable cannot be initialized in a file .h when two files .c do the include?

/* Isso em um arquivo .h */
int a = 5; // Da erro
static int b = 5; // Nao da erro

/* Arquivo .c 1*/
#include "arquivo.h"

/* Arquivo .c 2 */
#include "arquivo.h"

The static of the above code for some reason is mandatory when two files .c do the include, but it wouldn’t be redundant to use the static since the lifetime of these variables will not change?

1 answer

7


Global is a somewhat ambiguous term. Their lifespan is global, in fact.

But their visibility is quite different. The traditionally declared non-local variable has really global visibility. But when she gets a qualifier static the visibility is only of the source file of the code that it is declared, IE, only functions contained in this file will be able to see and access this variable.

So when you put the static the variable ceases to be totally global (does not change the life time) and allows you to use in different files what you think is the same variable, but are two different, with the same name, with different scopes.

Both are not recommended in most situations. You can use it if you really need to and know a lot what you are doing.

Behold What is the difference between scope and lifetime?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.