Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C -- Modify const through aliased non-const pointer

Is it allowed in standard C for a function to modify an int given as const int * using an aliased int *? To put it another way, is the following code guaranteed to always return 42 and 1 in standard C?

#include <stdio.h>

void foo(const int *a, int *b)
{
    printf("%d\n", *a);
    *b = 1;
    printf("%d\n", *a);
}

int main(void)
{
    int a = 42;
    foo(&a, &a);
    return 0;
}
like image 578
reffox Avatar asked Mar 14 '23 17:03

reffox


1 Answers

In your example code, you have an integer. You take a const pointer to it, and a non-const pointer to it. Modifying the integer via the non-const pointer is legal and well-defined, of course.

Since both pointers are pointers to integers, and the const pointer need not point to a const object, then the compiler should expect that the value read from the const pointer could have changed, and is required to reload the value.

Note that this would not be the case if you had used the restrict keyword, because it specifies that a pointer argument does not alias any other pointer argument, so then the compiler could optimise the reload away.

like image 70
Iskar Jarak Avatar answered Apr 02 '23 12:04

Iskar Jarak