Variable static and #define

4

What is the difference between defining a static variable and using #define in C? Apparently the two have the same function, right?

    
asked by anonymous 10.11.2016 / 21:47

2 answers

5

#define is not actually part of the language. It is just a text that before the compilation will be exchanged for a value. It looks like a variable, but it is not. The value is what will be used. Obviously it can not be changed.

Usually used to avoid magic numbers , at least in that context.

A static variable is actually a storage location for the code. It can be changed. It will exist throughout the execution of the application, no matter where it has been declared. The declaration location defines the scope, the visibility of the variable, but not the lifetime.

So if it is inside a function, it will exist in all calls. Its value will remain between one call and another. This can be a danger in applications with concurrent access.

If it is in a file, it will have the same feature and can be accessed throughout the file.

If it is declared global (I do not recommend it) it can be accessed anywhere.

This example might help to understand:

#include <stdio.h>

#define constante 0

void funcao() {
    int variavel = constante; // se colocasse 0 aqui daria na mesma
    static int estatica = constante;
    variavel++;
    estatica++;
    printf("variavel = %d, estatica = %d\n", variavel, estatica);
}

int main() {
    for (int i = 0; i < 10; ++i) {
        funcao();
    }
}

See running on ideone .

See What is the difference between scope and lifetime?

    
10.11.2016 / 22:06
1

#define is a precompile command, these statements are executed before the compilation itself, and any set value can not be changed during the code.

variable statics on the other hand can undergo changes, however its value is protected beyond the boundaries in which the variable has been defined.

    
10.11.2016 / 22:20