سؤال

In other words, when is a "static const" equivalent to a "#define"? I searched a lot and can't find anything. This is very relevant for global initialization dependencies (I know, globals are evil, but life is evil too!).

I am sure the standard does not force, but it probably mentions it.

E.g.:

static const int a = 2;  // Always seen it as compile time
static const int b = 2 * a;  // Compile time
static const float c = 3.14;  // Compile time
static const float d = c * 1.1 ;  // I know the evils of compile time here, but I've seen it both ways (compile and run time)
static const char e = 'p' ;  // Compile time
static const int *f = NULL;  // Never really tried it :)
هل كانت مفيدة؟

المحلول

This is specified by C++11 3.6.2: constant initialization is performed...

if an object with static or thread storage duration is not initialized by a constructor call and if every full-expression that appears in its initializer is a constant expression.

This is your situation, except for d: int and float don't have constructors, and the initializer is a literal, which is a constant expression. Constant initialization is part of static initialization, and:

Static initialization shall be performed before any dynamic initialization takes place.

The standard doesn't explicitly prescribe an implementation, but there is no ordering of static initializations, and it is understood that the initial values are essentially provided at load time, and no code executes in order to get those global variables to have their initial values.

The variable d does not meet these criteria since its initializer is not a constant expression (because c is not a constant expression). The standard allows d to be initialized either dynamically or statically.

نصائح أخرى

Answering: 'In other words, when is a "static const" equivalent to a "#define"?'

Never, the first is part of the programming language, the latter is a preprocessor text processing directive.

Declaring static const vs a define are two different things. A value replaced by define can non-const and non-static.

#MY_VAR 9
static const int a = MY_VAR;
int b = MY_VAR;

Defines essentially precompile time string replacement. Static and const keywords work all together different.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top