karthikbalaguru <ka************ ***@gmail.comwr ites:
Only 'const' provides the 'Read-only' functionality in C .
Not really true.
Sorry, i should have used that in a clear fashion.
For true compile-time constant , we need to use '#define' or perhaps
'enum'.
For run time constants, we need to use 'const' telling that it can not
be manipulated/changed.
I think, the above is true now.
Is there something else that makes it false ?
Remember that "const" doesn't really mean "constant"; it merely means
"read-only". For example, 42 is a constant, but:
const int x = 42;
x is not a constant; it's merely read-only. (But the compiler can
choose to store x in read-only memory, or not store it at all if its
address is never used; nevertheless, x can't be used where a constant
expression is required.)
Attempting to *directly* modify something declared as "const" is
illegal (a constraint violation, requiring a diagnostic):
x = 43; /* ILLEGAL */
If you attempt to *indirectly* modify something declared as "const",
the compiler isn't required to complain, but the behavior is
undefined:
int *ptr = (int*)&x; /* the cast discards the "const"; bad idea */
*ptr = 43; /* UNDEFINED BEHAVIOR */
A string literal is not "const" (for historical reasons) but any
attempt to modify the contents of a string literal also invokes
undefined behavior. This isn't because it's const (it isn't); it's
because the standard explicitly says that it's undefined behavior.
The language would be a bit cleaner if string literals actually were
"const", but that would have broken old code written before "const"
was introduced to the language.
If you write:
char *s = "hello"; /* DANGEROUS */
you're treading on dangerous ground. The initialization is legal,
because the string literal isn't const, but it means that the compiler
isn't required to complain if you try to modify *s or s[0]. Doing so
might happen to work, or it might blow up in your face. To be safe,
*pretend* that string literals are really const:
const char *s = "hello"; /* BETTER */
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"