Gestorm <zh********@126.comwrites:
Hi everyone, I have a problem. If I declare a struct with a const
member, what will happen?For example:
if I declared a struct like following:
struct{
const int a;
char c;
}aStruct;
then such statement as
aStruct.a = 0;
is illegal.
But I can printf the value of a, it's always the same value no matter
how many times I recompile the program. I'm wondering about how can
the compiler ascertain the value of the const member?
In an application, I wanna define a struct, whose first member is a
const and its value is given by me, how can I do that? Neither K&R
book nor "C: A Reference manual" mention this problem. Does anyone
know? Thanx ^_^
An object declared as "const" has the value given to it when it's
initialized. That value cannot legally be changed later by an
assignment.
You didn't tell us where you declared "aStruct". It's (almost) always
best to post a complete compilable program that demonstrates your
point.
If aStruct is declared outside any function, or with the "static"
keyword, then the initial value of aStruct.a will be 0. If it's
declared inside a function with no "static" keyword, its initial value
will be garbage, and you won't be able to assign a valid value. (It's
not unlikely that the garbage will happen to be 0, but don't depend on
it.)
Applying "const" to members of struct actually isn't very common in my
experience. But here's a small program that might suggest how it
could be useful:
#include <stdio.h>
struct person {
const int birth_year;
int current_age;
};
int main(void)
{
struct person fred = { 1970, 38 };
printf("fred.birth_year = %d, fred.current_age = %d\n",
fred.birth_year, fred.current_age);
/* Can't change fred.birth_year */
fred.current_age ++;
printf("fred.birth_year = %d, fred.current_age = %d\n",
fred.birth_year, fred.current_age);
return 0;
}
birth_year must be set when the person object is created, and cannot
be changed thereafter. current_age can change over time.
(A flaw in this is that C lets you get away with *not* initializing
birth_year; if you don't initialize it, you can't set it later.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"