开发者

Accessor function taking a const arg but returning non const pointer in C

seeking some advice here.

I have a structure which contains a pointer to another struct开发者_StackOverflow中文版ure, something like this:

struct item
{
    int type;
    struct user *owner;
};

I also have accessor functions, like this:

int item_get_type(const struct item * i);
struct user * item_get_owner(const struct item * i);

My question is about the second of these functions: Does this violate any rules or best practices with regard to the use of const?

The reason I use const here is to signify that the accessor function will not modify the structure passed in to it, but the caller is allowed to modify the returned structure. Am I better off dropping the const in the argument?


It's absolutely fine, and it correctly indicates your stated intention.


In addition, even if it is easy for a user to modify the structure it is still good to use const as it will help the compiler to optimize the code in the function. The compiler will know it never needs to modify the structure inside the function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜