Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is static needed when declaring const globals?

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?

like image 973
NoSenseEtAl Avatar asked Dec 27 '12 10:12

NoSenseEtAl


2 Answers

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

like image 52
James Kanze Avatar answered Nov 07 '22 06:11

James Kanze


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.

like image 24
rholmes Avatar answered Nov 07 '22 07:11

rholmes