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?
const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.
We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With