The const keyword and structures

K

kelvSYC

If you have an instance of a struct that's marked const, does the const
keyword mean that all of its members are read-only? What if you wanted
a struct where some members are constants and a few others you could
change?

Example:

struct foo {
const int a;
int b;
int (*c)(void);
}

const struct foo bar;

bar.a is constant
Is bar.b constant?
How about bar.c?

What if you wanted to have a structure where a and c are constant, and
b could be changed? Would you have to remove the const when declaring
bar?
 
M

Mike Wahler

kelvSYC said:
If you have an instance of a struct that's marked const, does the const
keyword mean that all of its members are read-only?

It means the struct object cannot be modified.
What if you wanted
a struct where some members are constants and a few others you could
change?

Example:

struct foo {
const int a;
int b;
int (*c)(void);
}

const struct foo bar;

bar.a is constant
Is bar.b constant?

Yes, by implication (the whole object 'bar' is const).
How about bar.c?

Same thing.
What if you wanted to have a structure where a and c are constant, and
b could be changed? Would you have to remove the const when declaring
bar?

Yes.

-Mike
 
N

Noah Roberts

kelvSYC said:
If you have an instance of a struct that's marked const, does the const
keyword mean that all of its members are read-only? What if you wanted
a struct where some members are constants and a few others you could
change?

Example:

struct foo {
const int a;
int b;
int (*c)(void);
}

const struct foo bar;

bar.a is constant
Is bar.b constant?
How about bar.c?

Yes, but if you declaired it like, "struct foo bar;" then it wouldn't be.

NR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top