First of all, why won't your example compile? If you couldn't compare constants, they would be kind of useless.
I would classify this as a waste of time. If something external to your program is modifying your memory, then what's to stop it from also modifying the memory you store your comparison at? In your example, that test could fail not because PI
changed, but because 3.1415
did... that number is stored somewhere, after all.
If your program changes the value of PI
, then it is broken, and you can't be sure the test works reliably anyhow. That's firmly undefined behavior, so anything goes. Its a lot like testing if a reference parameter references null... a well defined program can not possibly result in the test failing, and if it could pass you can't be sure the program is in a functioning state anyhow, so the test itself is a waste of time.
In either case, the compiler will probably decide that the test is a waste of time, and remove it all together.
Now, there is one situation that is slightly different from what you originally stated, which might be what your source was refering to. Consider the following code:
void external_function();
void internal_function(const int& i) {
cout << i << "...";
external_function();
cout << i;
}
Within internal_function
, the compiler can not assume that both outputs are identical. i
could be a reference to an integer that is not actually const
, and external_function
could change it. The key difference here is that i
is a reference, whereas in your original question PI
is a constant value.
int pi = 3;
void external_function() { pi = 4; }
void internal_function(const int&);
int main() {
internal_function(pi);
}
That will result in 3...4
being printed. Even though i
is a constant reference, the compiler has to assume it might change because something it can't see might change it.
In that case, such a test might be useful under certain circumstances.
void internal_function(const int& i) {
const int original_i = i;
cout << i << "...";
external_function();
cout << i << endl;
if(i != original_i) cout << "lol wut?" << endl;
}
In this case, the test is useful. original_i
is guarenteed to have not changed [and if it has, see the first half of this answer], and if i
has changed the assertion will fail.