2

Suppose in C I have the functions

type* func (type*);
const type* func_const (const type*);

such that they both have the exact same internal logic.

Is there a way I can merge the two into one function, where if given a const type, it returns a const type; and if given a non-const type, it returns a non-const type? If not, what is a good way of dealing with this? Define one in terms of the other via explicit casting perhaps?

0

2 Answers 2

10

You can't automate it, but you can certainly have the logic in a single location:

const type* func_const (const type*)
{
    /* actual implementation goes here */
}

type* func (type* param)
{
    /* just call the const function where the "meat" is */
    return (type*)func_const(param);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Do like the standard C library functions do and just take a const-qualified argument while returning a non-const-qualified result. (See strchr, strstr, etc.) It's the most practical.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.