I've read that static variables are used inside function when one doesn't want the variable value to change/initialize each time the function is called. But what about defining a variable static in the main program before "main" e.g.
#include <stdio.h>
static double m = 30000;
int main(void)
{
value = m * 2 + 3;
}
Here the variable m has a constant value that won't get modified later in the main program. In the same line of thought what difference does it make to have these instead of using the static definition:
const double m = 30000;
or
#define m 30000 //m or M
and then making sure here to use double operations in the main code so as to convert m to the right data type.
static
means that the variable will have static storage duration, and local visibility. In this case, it's being used for the "local visibility" part of that -- i.e. it means thatm
is visible only within this translation unit (essentially this file after it's prepocessed).The main difference is that with #define you leave the type system. The preprocessor has no notion of type safety, scope etc. So e.g. if you later try to write a loop like
for (int m = 0; m < size; m++) { ... }
you are up to a nasty surprise...
Also if you use #defines, you will only see the value of 30000 when debugging your code, not the name
m
. Which does not seem to make a big difference in this case, but when using meaningful constant and variable names, it does indeed.#define
is a preprocessor operation and will cause all occurrences ofm
to be replaced by30000
before the compilation phase happens. The other two examples are bona fide variables. Thestatic
variable exists in the translation unit in which it is declared and can be modified. Theconst
variable is read-only.