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
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.
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.
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.