[Dev-C++] "const_cast" Help please.....
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Farzan H. <far...@ho...> - 2005-04-15 08:26:29
|
Hi users, I've recently faced to some confusing results that "const_cast" makes. Let's assume we have the following code: const float i=3D55.5; float * j=3Dconst_cast<float*>(&i); cout << j << '\t' << &i << endl; // Displays addresses. *j=3D45.6; cout << *j <<'\t' << i << endl; // Displays contents. If you run the code you will see something like this: 0x22ff78 0x22ff78 45.6 55.5 As you can see, the address of "i" is "0x22ff78" and it is the place wher= e =20 "j" points to it. The value of "i" is 55.5 but the value of the place where "j" points to i= t =20 is 45.6!! How can a single memory block store two different values???? Now there is another strange result. If you assign 45.6 to "j" immediatel= y =20 after "const_cast" (instead of assigning after displaying addresses) like this: const float i=3D55.5; float * j=3Dconst_cast<float*>(&i); *j=3D45.6; cout << j << '\t' << &i << endl; // Displays addresses. cout << *j <<'\t' << i << endl; // Displays contents. the result will be: 0x22ff78 0x22ff78 55.5 55.5 I should mention that this distinction is made when you use DEV-C++ 5.If = =20 you use DEV-C++ 4, only the first result will be produced for both codes. I also tested the codes in MS Visual C++ 6 and it showed me the following= =20 result for both: 0012FF7C 0012FF7C 45.6 45.6 The value of "i" is 45.6 now. I think it is more acceptable result becaus= e =20 by using "const_cast", a constant storage (i) has been converted to a non constant= =20 storage (j) and you can change its content. Now please explain these results. Thanks, --=20 Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ |