c++ - practices - Can adding 'const' to a pointer help the optimization?

const reference c++ (4)

I have a pointer int* p, and do some operations in a loop. I do not modify the memory, just read. If I add const to the pointer (both cases, const int* p, and int* const p), can it help a compiler to optimize the code?

I know other merits of const, like safety or self-documentation, I ask about this particular case. Rephrasing the question: can const give the compiler any useful (for optimization) information, ever?

I think the compiler can't do much in your scenario. The fact that your pointer declared as const int * const p doesn't guarantee that the memory can't be changed externally, e.g. by another thread. Therefore the compiler must generate code that reads the memory value on each iteration of your loop.

But if you are not going to write to the memory location and you know that no other piece of code will, then you can create a local variable and use it similar to this:

const int * p = ...
int val = *p;
/* use the value in a loop */
for (i = 0; i < BAZILLION; i++)

Not only you help potential readers of your code to see that the val is not changed in a loop, but you also give the compiler a possibility to optimize (load val in a register, for instance).

It can help or it can make no difference or it can make it worse. The only way to know is to try both and inspect the emitted machine code.

Modern compilers are very smart so they can often deduce that memory is unchanged without any qualifiers (pr they can deduce many other optimizations are possible without code being written in manner easier to analyze) yet they are rather complex and so have a lot of deficiencies and often can't optimize every possible thing at every opportunity.

Using const is, as everyone else has said, unlikely to help the compiler optimize your loop.

It may, however, help optimise code outside the loop, or at the site of a call to a const-qualified method, or to a function taking const arguments.

This is likely to depend on whether the compiler can prove it's allowed to eliminate redundant loads, move them around, or cache calculated values rather than re-calculating them.

The only way to prove this is still to profile and/or check the assembly, but that's where you should probably be looking.

While this is obviously specific to the implementation, it is hard to see how changing a pointer from int* to int const* could ever provide any additional information that the compiler would not otherwise have known.

In both cases, the value pointed to can change during the execution of the loop.

Therefore it probably will not help the compiler optimize the code.