When I do declaration in C++ ,
static const int SECS = 60 * MINUTE;
const static int SECS = 60 * MINUTE;
is there any difference between these two?
is there any difference between these two?
No. Not at all. The order doesn't matter (in this case!).
Moreover, if you write this:
const int SECS = 60 * MINUTE; //at namespace level
at namespace level, then it is equivalent to this:
static const int SECS = 60 * MINUTE;
Because at namespace level const
variables has internal linkage by default. So the static
keyword doesn't do anything if const
is already there — except for increasing the readability.
Now what if you want the variable to have external linkage and const
at the same time, well then use extern
:
//.h file
extern const int SECS; //declaration
//.cpp file
extern const int SECS = 60 * MINUTE; //definition
Hope that helps.
const
always applies to the type to its immediate left; if there is none, it applies to the next type on its right.
So the following three declarations
const static int SECS = 60 * MINUTE;
// or
static const int SECS = 60 * MINUTE;
// or
static int const SECS = 60 * MINUTE;
are all equal. static
applies to the whole declaration; and const applies to the int
type.
The position of const
would only make a difference if you had a "more complicated" type, like e.g. a reference or a pointer:
int a;
const int * b = a; // 1.
int * const c = a; // 2.
In this case there is a difference between the place of const
- for 1. it applies to the int (i.e. it is a pointer to a const int, i.e. you can't change the value), and for 2., it applies to the pointer (i.e. you can't modify where c points to).
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