Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is modifying an object through a pointer to const undefined behavior?

Suppose we have an int variable referenced as const int*which in turn is aliased as int *. Is it clear from the Standard if modifying the variable through the int * pointer is undefined behavior or not?

As an illustration, consider the following code:

void increment(int* p) {
    (*p)++;
}

void call_increment(const int* p) {
    increment(p);
}

int main(void) {
    int x = 7;
    int* p = &x;

    call_increment(p);
}
like image 548
jinawee Avatar asked Dec 22 '22 22:12

jinawee


1 Answers

Modifying an object through a pointer to const is ill-formed, not undefined behavior.
Fixing that by casting away the const is well-formed unless the object referred to is actually const.

Your code has a different problem:
You are discarding a const-qualifier when passing p from call_increment() to increment().

Any useful compiler will complain about that even without being prompted:

g++ -x c -std=c18 main.cpp && ./a.out
main.cpp: In function 'call_increment':
main.cpp:6:15: warning: passing argument 1 of 'increment' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
     increment(p);
               ^
main.cpp:1:21: note: expected 'int *' but argument is of type 'const int *'
 void increment(int* p) {
                ~~~~~^

Just heed it, and better ask for more with at least -Wall -Wextra.

like image 168
Deduplicator Avatar answered Dec 31 '22 01:12

Deduplicator