473,406 Members | 2,345 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

doubt in basic c++ code

hi,

i just started learning c++, and i tried this sample program. i
expected output to be 20 and 20 but i got 10 and 20. 'i' has not
changed, but the address of i and value of ptr are same. can some one
please clarify.

#include <iostream>
using namespace std;

int main()
{
const int i = 10;
int* ptr = const_cast<int*>(&i);
*ptr = 20;

cout << "i: " << i << endl;
cout << "ptr: " << *ptr << endl;
return 0;
}

TIA
fin.

Jun 14 '06 #1
7 1332
fi********@gmail.com wrote:
hi,

i just started learning c++, and i tried this sample program. i
expected output to be 20 and 20 but i got 10 and 20. 'i' has not
changed, but the address of i and value of ptr are same. can some one
please clarify.

#include <iostream>
using namespace std;

int main()
{
const int i = 10;
Ok, you defined a constant, i.e. an object that never changes.
int* ptr = const_cast<int*>(&i);
Here, you cast away the constness, effectively taking the responsibility to
never try to change it. The compiler cannot protect you from it anymore.
*ptr = 20;
And here, you try to change the constant. The result of that is undefined.
cout << "i: " << i << endl;
cout << "ptr: " << *ptr << endl;
return 0;
}

TIA
fin.


Jun 14 '06 #2
In addition to that, what happens using VC6, is optimization of the
code.
The compiler knows that 'i' is a constant and replaces its instances
through out the code with the initialized value.

Rolf Magnus wrote:
fi********@gmail.com wrote:
hi,

i just started learning c++, and i tried this sample program. i
expected output to be 20 and 20 but i got 10 and 20. 'i' has not
changed, but the address of i and value of ptr are same. can some one
please clarify.

#include <iostream>
using namespace std;

int main()
{
const int i = 10;


Ok, you defined a constant, i.e. an object that never changes.
int* ptr = const_cast<int*>(&i);


Here, you cast away the constness, effectively taking the responsibility to
never try to change it. The compiler cannot protect you from it anymore.
*ptr = 20;


And here, you try to change the constant. The result of that is undefined.
cout << "i: " << i << endl;
cout << "ptr: " << *ptr << endl;
return 0;
}

TIA
fin.


Jun 14 '06 #3
> In addition to that, what happens using VC6, is optimization of the
code.
The compiler knows that 'i' is a constant and replaces its instances
through out the code with the initialized value.


thats right !! compiler should replace the i occurences with the
value(constant folding - related to compiler optimization).

it is done in order to save memory. compiler will nt hv to allocate
memory for such const variables.

bt when we are dealing with the address of such const variables(as we
are in this case), it should allocate memory and thereby it should not
replace the occurences. (Theoretically).

I hv tried to run the code on several compilers, bt same problem.

Also when u use const or u use #define, the VC6 compiler generates same
assembly code for both. which is very confusing.

Jun 14 '06 #4
jackdorse wrote:
In addition to that, what happens using VC6, is optimization of the
code.
The compiler knows that 'i' is a constant and replaces its instances
through out the code with the initialized value.

thats right !! compiler should replace the i occurences with the
value(constant folding - related to compiler optimization).


That's what usually happens in practise. However, with respect to standard
C++, that doesn't matter much. This only important thing here is that the
result is undefined.
it is done in order to save memory.
Also to save execution time, because all calculations that are based on
constants can be done at compile time.
compiler will nt hv to allocate memory for such const variables.
That depends.
bt when we are dealing with the address of such const variables(as we
are in this case), it should allocate memory and thereby it should not
replace the occurences. (Theoretically).
It doesn't matter if the constant has a memory location or not. The compiler
can (and usually will) still choose to use the value directly wherever it
wants.
I hv tried to run the code on several compilers, bt same problem.

Also when u use const or u use #define, the VC6 compiler generates same
assembly code for both. which is very confusing.


Why?

Jun 14 '06 #5
Rolf Magnus wrote:
jackdorse wrote:
In addition to that, what happens using VC6, is optimization of the
code.
The compiler knows that 'i' is a constant and replaces its instances
through out the code with the initialized value.


thats right !! compiler should replace the i occurences with the
value(constant folding - related to compiler optimization).


That's what usually happens in practise. However, with respect to standard
C++, that doesn't matter much. This only important thing here is that the
result is undefined.
it is done in order to save memory.


Also to save execution time, because all calculations that are based on
constants can be done at compile time.
compiler will nt hv to allocate memory for such const variables.


That depends.
bt when we are dealing with the address of such const variables(as we
are in this case), it should allocate memory and thereby it should not
replace the occurences. (Theoretically).


It doesn't matter if the constant has a memory location or not. The compiler
can (and usually will) still choose to use the value directly wherever it
wants.
I hv tried to run the code on several compilers, bt same problem.

Also when u use const or u use #define, the VC6 compiler generates same
assembly code for both. which is very confusing.


Why?


In case of #define .. the compiler, simply replaces the occurences ...
tht is quite understood. But when it is const int i; there shud be some
memory location reserved, instead of merely replacing the occurences.
(Atleast when we are taking the address of it). (pls refer the assembly
code generated, u ll get a better idea)

i also tried printing the value using *(&i) --> bt still the compiler
replaces it with the value. (compilers can get a bit oversmart
sometimes ... :) )

Jun 14 '06 #6
jackdorse wrote:
Also to save execution time, because all calculations that are based on
constants can be done at compile time.
> compiler will nt hv to allocate memory for such const variables.
That depends.
> bt when we are dealing with the address of such const variables(as we
> are in this case), it should allocate memory and thereby it should not
> replace the occurences. (Theoretically).


It doesn't matter if the constant has a memory location or not. The
compiler can (and usually will) still choose to use the value directly
wherever it wants.
> I hv tried to run the code on several compilers, bt same problem.
>
> Also when u use const or u use #define, the VC6 compiler generates same
> assembly code for both. which is very confusing.


Why?


In case of #define .. the compiler, simply replaces the occurences ...
tht is quite understood. But when it is const int i; there shud be some
memory location reserved, instead of merely replacing the occurences.
(Atleast when we are taking the address of it).


Yes, when you are taking the address of it, the data might actually be put
into a memory location, dedpending on what you use the pointer for and on
how you defined the constant.
(pls refer the assembly code generated, u ll get a better idea)
What I know from having done so is that the compiler tends to do many
optimizations I didn't expect and not do optimizations I would have
expected. It's not wise to depend on the optimzation behavior of the
compiler.
i also tried printing the value using *(&i) --> bt still the compiler
replaces it with the value. (compilers can get a bit oversmart
sometimes ... :) )


If you want a real memory access, try to define the constant as volatile.
However, I don't think that this kind of working around your own
limitations (making an object that you plan to modify const) is something
to be ever considered.
Jun 14 '06 #7

"jackdorse" <ja*******@gmail.com> skrev i meddelandet
news:11**********************@c74g2000cwc.googlegr oups.com...
In addition to that, what happens using VC6, is optimization of the
code.
The compiler knows that 'i' is a constant and replaces its
instances
through out the code with the initialized value.


thats right !! compiler should replace the i occurences with the
value(constant folding - related to compiler optimization).

it is done in order to save memory. compiler will nt hv to allocate
memory for such const variables.

bt when we are dealing with the address of such const variables(as
we
are in this case), it should allocate memory and thereby it should
not
replace the occurences. (Theoretically).


But the C++ standard also says that you are not allowed to cast away
constness from an object that is actually declared const. If you do
that anyway, the compiler doesn't have to follow the rules either! :-)

If you do it like:

int i = 10;
const int* j = &i;
int* ptr = const_cast<int*>(j); // this is ok
*ptr = 20;

it will work. As the pointer j points to a variable that is not really
const, you can cast away the constness from the pointer.
Bo Persson
Jun 14 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: mahesh | last post by:
Hi all, I have a doubt with OOAD and Dialogs. I have a Dialog Class. tkSimple.py It contains a class body as below. Now I am calling the tkSimple.py in another python program and using the...
2
by: Baskar RajaSekharan | last post by:
Hi, I have a C# usercontrol which has an OCX in addition to combo, textboxes etc. i need to print the usercontrol. How could this be acheived? In VB there is one method called PrintForm . ...
20
by: Amit D.Shinde | last post by:
How can i add the scroll bar to my form if the controls are more. I am having lot of of coontrols on my form. for which my form is small. so i want to add the scroll bar to my form. Also if the...
1
by: mallikarjun | last post by:
I want to upload a tiff image using FTP I am using method 'inet.Execute()',what are the parameters should it contain? Iam getting 'License'exception to that ActiveX component. i had used the...
1
by: Runni | last post by:
hi I hav to upload data from office of one branch to another branch which is 15 KM apart only through VB.Net using Telephony as They Dont Hav the Web Server And They r convenient with...
38
by: edu.mvk | last post by:
Hi I am using strcpy() in my code for copying a string to another string. i am using static char arrays. for the first time it is exected correctly but the second time the control reaches...
9
by: yashu21985 | last post by:
Why won't this code compile? #include <iostream.h> void Print(int i); void Print(float f, int skip = 0); void main() { Print(3.3); } void Print(int i) {
2
by: ss0007 | last post by:
Hi everyone , I was testing the following piece of code and unable to proceed because the click() method is not invoked for the button's onclick event. The same function works fine in the...
4
by: lilly07 | last post by:
Hi, I have two text file as below: file1.txt (4 columns) test1 1000 2000 + test2 1000 2000 - test1 1000 2000 + test3 1000 2000 + test1 1000 2000 -
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.