Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between declaration 'static const' and 'const static'

Tags:

c++

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?

like image 368
Xin Yuan Avatar asked Dec 04 '22 08:12

Xin Yuan


2 Answers

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.

like image 137
Nawaz Avatar answered Dec 09 '22 15:12

Nawaz


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

like image 31
codeling Avatar answered Dec 09 '22 15:12

codeling