const keyword problem.

S

siliconwafer

Hi All,
If I declare an identifier with a const keyword and not initilize
it.Then later on I assign it value of an expression.Is it fine?
I feel yes.But if I modify the value of that constant like say an
operation like,
const int i;
int a,b;
i = a + b;
.....
i++;
Then my compiler(gcc 2.95.1) issues a warning.
If I neglect the warning and ontinue the operation,what will happen?
The value gets modified?
will it result in following run time error?
"segmentation fault"?
-Siliconwafer
 
J

Jack Klein

Hi All,
If I declare an identifier with a const keyword and not initilize
it.Then later on I assign it value of an expression.Is it fine?

No, it's not. If the const object has static storage duration, it
will be initialized to 0. If it has automatic storage it will remain
uninitialized forever.
I feel yes.But if I modify the value of that constant like say an

Fortunately for the rest of us, the C language is not defined by what
you feel. It is defined by an International Standard.
operation like,
const int i;
int a,b;
i = a + b;
....
i++;
Then my compiler(gcc 2.95.1) issues a warning.

And it is quite right to do so, since the C language standard requires
the compiler to issue a diagnostic.
If I neglect the warning and ontinue the operation,what will happen?

The C standard doesn't know and doesn't care. Attempting to modify a
const object produces undefined behavior. C places no requirements at
all on what happens when you produce undefined behavior. You have
left the planet C and you are lost in space on your own.
The value gets modified?
will it result in following run time error?
"segmentation fault"?

Reformat your hard disk? Knock tiles off the space shuttle? On the
DeathStation 9000, a mechanical arm comes out and punches the
programmer to discourage him from doing it again.

What happens when you produce undefined behavior is not a language
issue.
 

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,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top