Re: const int value changing....



In article <1124688926.558688.45670@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
"shyju_kambi" <n.shyju@xxxxxxxxx> wrote:

> when a 'const int ' is declared, where is it been created(in RAM?)
>
> #include<stdio.h>
> int main()
> {
> const int i=10;
> const int *p;
> p=&i;
> *p=12;
> printf("\n %d %d",i,*p);
> return 0;
> }
>
> ---------------------------------------------------------
> the following program i tryied, still i was unable to change the value
> of a const.
>
> when a variable is declared, a ram location is allocated for it.

It seems you have a little knowledge how computers work. A little
knowledge can be very very dangerous. Forget about "ram locations".
Download a copy of the C Standard, or at least a copy of the last draft
of the C Standard, and use that as a reference. You won't find "ram
locations" mentioned there anywhere.

> then
> why i cant change the value of that variable using pointer?
>
> if the variable i've declared as a 'static int ' then using pointer i
> can change the value.
>
>
> plz give solutions

Solution? Don't do it.

In many cases, the compiler won't allow you to modify a const variable.
However, you can trick the compiler into allowing code that attempts to
modify such a const variable.

Any code that attempts to modify a const variable invokes UNDEFINED
BEHAVIOR. That means: Anything could happen. And that means _absolutely
anything_. If you modify a const variable, and as a result your harddisk
gets formatted, don't complain, it is your own fault. If it makes a
server crash and half a dozen people need a week to fix it, don't
complain, it is your fault.

(This will most likely not happen in a simple program that you write to
try out things. It will happen when you write a program that is used by
ten thousand customers, and then you are in trouble. )
.



Relevant Pages

  • Re: Is this legal?
    ... That it is the only way to initialise an 'const' ... | online Comeau snippet compiler. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: size_t problems
    ... since a function can't modify ... concern to the caller. ... It does if you are passing a pointer to a const item. ... void f(const int* const); ...
    (comp.lang.c)
  • Re: accessor member functions and const
    ... I want to be able to reference the returned ... const int& getValconst ... so one cannot modify the object via the reference. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: const bei Parametern egal?
    ... void bar (const int i); ... hatte ich eigentlich eine Compiler-Fehlermeldung wegen des fehlenden const in der Definition von foo::barerwartet. ... the const and volatile typespecifiers ... for each parameter type are ignored ...
    (microsoft.public.de.vc)
  • Re: problem about const member in a struct
    ... if I declared a struct like following: ... the compiler ascertain the value of the const member? ... const int birth_year; ...
    (comp.lang.c)