Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!uunet!etnibsd!vsh From: vsh@etnibsd.UUCP (Steve Harris) Newsgroups: comp.lang.c++ Subject: Re: Constant Question Keywords: const Message-ID: <1103@etnibsd.UUCP> Date: 19 Jan 90 18:38:53 GMT References: <130286@sun.Eng.Sun.COM> <1405@mit-amt.MEDIA.MIT.EDU> Reply-To: vsh@etnibsd.UUCP (Steve Harris) Organization: Eaton Corp, Semiconductor Equipment Div., Beverly, MA Lines: 54 In article <1405@mit-amt.MEDIA.MIT.EDU> peter@media-lab.media.mit.edu (Peter Schroeder) writes: > In article <130286@sun.Eng.Sun.COM> rbogen%dreams@Sun.COM (Richard Bogen) writes: > > The definition of a constant is an identifier whose > > associated value cannot be modified (even through pointers). > > Yet when the following program is run the value printed is 0.0. > > Can anyone give me a "pointer" to what is happening here? > > > > main() > > { > > const float PI = 3.14159; > > float *const ptr = &PI; > > *ptr = 0.0; > > printf("%PI = %f\n",PI); > > } > > What you declared is not a pointer to a const, but a const pointer. Hence > you can not assign to the this const pointer another address, but you can > modify what it points to. > > What you want is: > main() > { > const float PI = 3.14159; > const float *ptr = &PI; > *ptr = 0.0; // error > printf("%PI = %f\n",PI); > } > > Peter > peter@media-lab.media.mit.edu =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Peter corrected the code, but didn't answer the question! Isn't the real problem in line 2, not line 3? Clearly, ptr is a const pointer to a (variable) float. The pointer is constant, but the thing pointed to is modifyable. In line 2, you declare this pointer and initialize it to point to PI. However, PI is a const float, not modifyable. Shouldn't the compiler refuse to allow you to initalize (or assign) a pointer (const or otherwise) to a const float? Shouldn't the compiler insist that the pointer be of type "const float *"? My g++ generates a warning at line 2, and creates a second object for ptr to point to, so PI remains unchanged and *ptr is initalized to 3.14159 but then is changed to 0.0. -- Steve Harris - Eaton Corp. - Beverly, MA - uunet!etnibsd!vsh