often in headers I see
//global namespace, not in class
static const int my_global =1984;
but recently I learned that const implies internal linkage, so I wonder doesnt that make static unnecessary?
It depends. In C++, it's unnecessary, but some people (myself included) like to put it in, on the grounds of saying what we mean. And of course, if the header is to be used in C as well, it is necessary (but for many uses in C, you'll need a #define
).
In C++, it is unnecessary (redundant) to have the static keyword to prevent global linkage, since const does this for standard C++ (C++98, C++03, C++11). In C, however, the static keyword is necessary for a variable to have local (file) linkage. Since many C coding practices have been carried into C++ by habit (there is a lot of overlap), some people may bring this habit over without thinking. I've heard it argued that the redundant static keyword in C++ to indicate non-global linkage helps C programmers understand.
I myself prefer the precision of programming in C++ with C++ idioms, so that we don't perpetuate C code in C++, which can lead to subtle errors, or at least waste and redundant code (such as habitual checking for NULL prior to calling delete on a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With