Reputation: 3411
The sentence is part of paragraph §3.2/2 :
A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied.
What exactly does the sentence in bold mean above?
Edit:
The answer to the question of which this one is considered a duplicate, doesn't say anything that could answer my question.
Upvotes: 6
Views: 328
Reputation:
It means that when you use a constant as a constant, it's just like you were actually using a constant.
struct S {
static const int i = 0;
};
int main() {
return S::i;
}
Although S::i
has an initialiser, it has no definition, but the text in your question makes a special exception for uses like this, where S::i
is only accessed for its value. In that case, no definition is needed.
On the other hand, other uses do require a definition:
struct S {
static const int i = 0;
};
int f(const int &i) {
return i;
}
int main() {
return f(S::i);
}
This program is invalid, and is accepted by some implementations, but rejected by others. The call to f
requires an actual definition of S::i
to exist, although if f
gets inlined, it's possible for the lack of a definition to go undiagnosed.
On my system, if compiling and linking the second program without optimisations, I get:
$ g++ test2.cc -o test2 /tmp/ccdEsfxs.o:test2.cc:function main: error: undefined reference to 'S::i' collect2: error: ld returned 1 exit status
To make it work, a definition needs to be provided, like so:
struct S {
static const int i = 0;
};
const int S::i;
Upvotes: 7