cconstantscompiler-optimizationpointer-aliasing

Is it safe to change data via a pointer when another pointer-to-const observes it?


Is it a safe code, or can the compiler optimize access through p, such that *p will result in 42?

#include <stdio.h>

int i = 42;
int *d = &i;

void test(int const *p) 
{
    *d = 43;
    printf("%d, %p\n", *p, (void *) p);
    printf("%d, %p\n", *d, (void *) d);
}

int main() {
    test(d);
    return 0;
}

I found out that *p is usually printed in 43, but I wonder if there are any pitfalls here, so that in some conditions printing *p could yield 42.


Solution

  • Is it a safe code, or can the compiler optimize access through p, such that *p will result in 42?

    Safe.

    if there are any pitfalls here, so that in some conditions printing *p could yield 42.

    No.

    The compiler, if it applies such optimizations, has to be aware that you are modifying a global variable that may be aliased via another pointer and has to recompute the result at each access. const pointer only means that you cannot modify the memory using that pointer. You may consider researching restrict keyword and aliasing in C programming language.