This behavior is undefined to change the value, which I also have a const pointer pointing to

Are there any undefined behavior in the following scenario?

void do_stuff(const int *const_pointer, int *pointer) {
    printf("%i\n", *const_pointer);
    *pointer = 1;
}

int data = 0;
do_stuff(&data, &data);

If this behavior is undefined, it can cause problems if the compiler assumes that the value that const_pointerindicates never changes. In this case, he can change the order of both teams in do_stuffand thereby change the behavior from the intended printf("0")to printf("1").

+4
source share
2 answers

If the compiler can prove that the pointer of the value by the pointer to const does not change, it will not need to reload the value or keep order.

, , , . ( , , .)

undefined, , printf 0.

+2

A const_pointer , , , .

, , const . const - . const . , strcpy :

strcpy( char *s, const char *t );

,

strcpy( char *s, char *t ); // without const, still work, just not as good as the first version

: const_pointer, pointer ( ).

0

All Articles