While it is true that the behavior is well-defined - it is not true that compilers can "optimize for const" in the sense that you mean.
That is, a compiler is not allowed assume that just because a parameter is a const T* ptr
, the memory pointed to by ptr
will not be changed through another pointer. The pointers don't even have to be equal. The const
is an obligation, not a guarantee - an obligation by you (= the function) not to make changes through that pointer.
In order to actually have that guarantee, you need to mark the pointer with the restrict
keyword. Thus, if you compile these two functions:
int foo(const int* x, int* y) {
int result = *x;
(*y)++;
return result + *x;
}
int bar(const int* x, int* restrict y) {
int result = *x;
(*y)++;
return result + *x;
}
the foo()
function must read twice from x
, while bar()
only needs to read it once:
foo:
mov eax, DWORD PTR [rdi]
add DWORD PTR [rsi], 1
add eax, DWORD PTR [rdi] # second read
ret
bar:
mov eax, DWORD PTR [rdi]
add DWORD PTR [rsi], 1
add eax, eax # no second read
ret
See this live on GodBolt.
restrict
is only a keyword in C (since C99); unfortunately, it has not been introduced into C++ so far (for the poor reason that it is more complicated to introduce in C++). Many compilers do kinda-support it, however, as __restrict
.
Bottom line: The compiler must support your "esoteric" use case when compiling f()
, and will not have any problem with it.
See this post regarding use cases for restrict
.