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.
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.
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