typedef struct
{
int a;
int b;
} my_struct_t;
void f2(const my_struct_t *my_struct, int *b)
{
*b = my_struct->a + 1;
}
void f1(my_struct_t *my_struct)
{
f2(my_struct, &(my_struct->b));
}
The my_struct
parameter in f2()
is declared as const
so none of its members can be modified, but the b
parameter is a pointer to a member of my_struct
which is modified.
I wonder if, according to the c99
standard, the way I called f2()
is legal or could lead to undefined behavior?
This behavior is allowed.
The const
qualifier on the first parameter says the struct it points to cannot be modified through that pointer. It doesn't prevent the member from being modified through a non-const pointer.
And because the object itself is not const
qualified, it is allowed to modify *b
in the function.
In fact, because of that, it would also be allowed to cast the my_struct
parameter to a non-const pointer and modify the members that way, although doing so would generally be considered bad form.