Variable Static and #define

Asked

Viewed 5,592 times

5

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

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

8

#define actually not even 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 will be used. Obviously it cannot be exchanged.

It is usually used to avoid magic numbers, at least in that context.

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

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

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

If it is declared global (not recommended) it can be accessed anywhere.

This example can help 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();
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Behold What is the difference between scope and lifetime?

1

#define is a pre-build command, these instructions are executed before the compilation itself and any value set cannot be changed in the course of the code.

variables statics on the other hand may suffer changes, however its value is saved beyond the borders at which the variable was defined.

Browser other questions tagged

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