Static, define, and const in C

前端 未结 9 2015
半阙折子戏
半阙折子戏 2020-12-13 04:52

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 def

相关标签:
9条回答
  • 2020-12-13 05:36

    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.

    0 讨论(0)
  • 2020-12-13 05:40

    In the toplevel scope static means that the variable (or function) cannot be accessed outside this source file - it won't be made available to the linker, and won't cause any name conflicts when linked in. It has no effect on whether a variable is constant or not - in fact, such variables are often specifically non-constant so that initialization can be cached.

    The difference between using const and #define is that the former allows the compiler to type-check your usage of a constant.

    0 讨论(0)
  • 2020-12-13 05:44

    When you write const double m=3000; you are telling the compiler to create a symbol m in the object file that can be accessed from other files. The compiler may inline the value of m in the file where it is defined, but the symbol still has to be allocated for the purposes of separate compilation.

    When you write #define m 3000 you are just using a syntactic convenience for writing the same constant in several places in the source file.

    0 讨论(0)
提交回复
热议问题