Felipe Lavratti
Felipe Lavratti

Reputation: 2967

Return const struct member as non const in C: ok or bad?

Is it ok or can it be considered a bad practice to return non const data member pointer from a const struct? What are the dangers of returning a non const pointer as shown below?

widget_t * widget_child(const widget_t * parent)
{
if (!parent)
    return NULL;

return parent->child;
}

Upvotes: 4

Views: 1710

Answers (3)

mfro
mfro

Reputation: 3335

The const keyword doesn't really define anything constant in C. What it says is basically a promise to the compiler: the const identifier will be treated readonly within this specific context. const should be read as readonly, this was bad naming from the beginning of C.

This will allow the compiler to do certain optimizations it couldn't do if it suspected the callee to modify this identifier within the called function.

Baseline is: this is perfectly legal since the promise is kept.

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45684

Whether it is acceptable to return a specific non-const data member from a const-qualified structdepends entirely on the semantics of the data-structure it is a part of.
It is not legally wrong, and C cannot say anything more on the subject.
You, as the programmer, who (hopefully) knows and understands the semantics are trusted (out of neccessity / for efficiency) to choose right.

Even if it was const-qualified, C deliberately allows you to override it if you are sure you are right and accept the consequences. This override takes the form of an explicit cast.

Upvotes: 1

guest
guest

Reputation: 6708

This is fine. Pointers themselves are values (it's an address, after all). You read that value from a const structure. That's fine. You return that value. That's also fine.

Upvotes: 0

Related Questions