user1224478
user1224478

Reputation: 355

Should const struct members change when sending it as a function parameter?

I have a struct:

typedef struct {
    int  age;
    char *Name;
    int  sex;
} PERSONAL_INFO;

I declare a struct using:

PERSONAL_INFO  *John;

and I want to send this struct into a function as a const bc I don't want any of the data to change.

void processInfo(const PERSONAL_INFO *person)
{
    //process information
}

Does this guarantee that the struct data members won't change? Or do I need to declare the data members as consts as well?

Upvotes: 2

Views: 635

Answers (2)

molbdnilo
molbdnilo

Reputation: 66459

The const guarantees to the author of the function that they can't accidentally change any members.

There's no guarantee to the caller of the function that it won't change any members, as the function's author can deliberately remove the const-ness with a cast.

To the function's caller, const is more of a promise by the function than a guarantee by the compiler.

However, even though the function can't change the value of the member Name without removing the const-ness of the parameter, it's free to change the value of whatever it points to, e.g. person->Name[0] = 0 is valid in any case.

If you want absolute guarantees, you can't pass the structure itself but need to use a (deep) copy of it.

Upvotes: 1

dbush
dbush

Reputation: 224457

It makes it harder to change the members but it's not a guarantee.

If you do this:

void processInfo(const PERSONAL_INFO *person)
{
    person->age = 0;
}

The compiler with throw an error:

error: assignment of read-only location

But if you do this:

void processInfo(const PERSONAL_INFO *person)
{
    PERSONAL_INFO *other_person = person;
    other_person->age = 0;
}

You'll only get a warning:

warning: assignment discards qualifiers from pointer target type

And if you ignore this warning, it won't stop you from changing the field.

Upvotes: 1

Related Questions