By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,966 Members | 2,054 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,966 IT Pros & Developers. It's quick & easy.

Understanding consant_cast in C++

P: 2
Hi
in the bellow program both p and &i contains the address of same location .
But they are giving different value when i dereferenced it. I am confused .if any one know the solution please reply.

#include<iostream>
using namespace std;
int main()
{
const int i=10;
int *p=const_cast<int *>(&i);
*p=200;
cout<<p<<" "<<*p<<endl;
cout<<&i<<" "<<i<<endl;
return 0;
}
Jun 20 '07 #1
Share this Question
Share on Google+
5 Replies


DeMan
100+
P: 1,806
Hi oecean,

Welcome to thescripts. I'm sure you will find a wealth of information on a variety of topics available here.
As this question is c/c++ related, I will move it to the appropriate forum (where it will be exposed to experts who may better be able to answer it).
In future, you can find your way to different forums by selecting options from the links on the blue bar near the top of the screen.

I'm sure the c(++) experts will be more than happy help you!
Jun 20 '07 #2

Expert 100+
P: 181
Hi
in the bellow program both p and &i contains the address of same location .
But they are giving different value when i dereferenced it. I am confused .if any one know the solution please reply.

#include<iostream>
using namespace std;
int main()
{
const int i=10;
int *p=const_cast<int *>(&i);
*p=200;
cout<<p<<" "<<*p<<endl;
cout<<&i<<" "<<i<<endl;
return 0;
}
Might be compiler optimization. If you go through constants in thinking in c++(available freely in net) it says in some places like
const int i = 100;
cout<<i;
the compiler might replace i with 100;
Jun 20 '07 #3

Meetee
Expert Mod 100+
P: 931
Hi
in the bellow program both p and &i contains the address of same location .
But they are giving different value when i dereferenced it. I am confused .if any one know the solution please reply.

#include<iostream>
using namespace std;
int main()
{
const int i=10;
int *p=const_cast<int *>(&i);
*p=200;
cout<<p<<" "<<*p<<endl;
cout<<&i<<" "<<i<<endl;
return 0;
}
Which different values you are talking about? I am getting output
0xbfb5ad08 200
0xbfb5ad08 10

both have the same address.

Best regards.
Jun 20 '07 #4

Meetee
Expert Mod 100+
P: 931
Which different values you are talking about? I am getting output
0xbfb5ad08 200
0xbfb5ad08 10

both have the same address.

Best regards.
I m sorry, the output is
0xbfb5ad08 200
0xbfb5ad08 200

as *p points to &i, both will have the same value which is *p =200

regards
Jun 20 '07 #5

weaknessforcats
Expert Mod 5K+
P: 9,197
Please do not double post.

I have already responded to this.
Jun 20 '07 #6

Post your reply

Sign in to post your reply or Sign up for a free account.