I do not understand the difference between these two statements in my C++ class:
class MyClass {
public:
private:
const static int var = 0; // Option 1
static const int var = 0; // Option 2
};
What is the difference b/w Option 1 and Option 2?? They both compile.
They are the same. But I would always go for option 2 for a simple reason that the keywords
const
andint
fit better when juxtaposed as they define the datatype. Where as the keywordstatic
defines the accessibility of that variable.They mean exactly the same thing. You're free to choose whichever you think is easier to read.
In C, you should place
static
at the start, but it's not yet required. I'm not sure if C++ followed C in this regard.They are the same. See this discussion: http://bytes.com/topic/c/answers/140177-const-static-vs-static-const
static
,const
(here, anyway) and the type (e.g.int
) are all part of the declaration specifier. Historically, the declaration specifier was an unordered list of keywords and type names, so:were all legal, and all meant the same thing.
I think that this is still the case, both in C and in C++, but if I'm not mistaken, C has deprecated putting the storage class specifier (
static
) any where but at the beginning. This is at any rate an almost universal convention, so you should normally put thestatic
(andextern
, etc.) at the start.Note too that being unordered only applies to the declaration specifier. Within the declarators which follow, the cv-qualifier(s) must follow what they qualify; for reasons of orthogonality, you should normally always put the cv-qualifiers after what they modify (i.e.
int const
, and notconst int
).Finally, it seems to be a widespread convention to present the type modifiers before the type, with the signedness modifier (
signed
orunsigned
) preceding the length modifier (short
,long
orlong long
). It's also fairly frequent to drop theint
if a modifier is present, so people writeunsigned
, rather thanunsigned int
, andlong
, rather thanlong int
. This is far from universal, however.Given this, the first way the declaration is written, above, is preferred, although it is quite acceptable to drop the
int
.