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);
}
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
.
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