Dominique Dominique - 11 months ago 58
C Question

How to deal with const propagation in subfunctions

I need to to a modification in an existing function, having some

input parameters:

int f(const owntype *r1, const owntype *r2)

In order to do this, I would like to call a subfunction, who is using the same type, but without the

void subfunction (owntype *src, owntype *dst)

I've already tried this (along with quite some other variants), but it does not work:

int f(const owntype *r1, const owntype *r2) {
subfunction((const owntyp*) r1);

How can I get this to compile without needing to change the parmeter description of both functions?

Answer Source

As long as subfunction does not attempt to write to the pointed-to objects *r1 and *r2 it's alright to call it through a cast:

subfunction(owntype*)r1, (owntype*)r2);

The standard(ยง6.7.3) says:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

So, reading from it is fine, as long as you don't write to it.