Static, define, and const in C

2019-01-22 03:39发布

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.

9条回答
老娘就宠你
2楼-- · 2019-01-22 04:17

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 that m is visible only within this translation unit (essentially this file after it's prepocessed).

查看更多
混吃等死
3楼-- · 2019-01-22 04:17

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.

查看更多
Root(大扎)
4楼-- · 2019-01-22 04:18

#define is a preprocessor operation and will cause all occurrences of m to be replaced by 30000 before the compilation phase happens. The other two examples are bona fide variables. The static variable exists in the translation unit in which it is declared and can be modified. The const variable is read-only.

查看更多
登录 后发表回答