473,883 Members | 2,112 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Surprising Problem

Hello Friends
Can anyone help me where exactly at what address the *p is storing the
updated value ( which is 99).

const int k=9;

int *p=(int *)&k;

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k

cout<<"Addreses \n"<<&(*p)<<& k; //BOTH the addresses are same.

cout<<"values \n"<<*p<<k; //But still the values are differentl.

what exaclty is happening here...??
Thanks

Jul 25 '06 #1
7 1431
co******@gmail. com wrote:
Hello Friends
Can anyone help me where exactly at what address the *p is storing the
updated value ( which is 99).

const int k=9;

int *p=(int *)&k;

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k

cout<<"Addreses \n"<<&(*p)<<& k; //BOTH the addresses are same.

cout<<"values \n"<<*p<<k; //But still the values are differentl.

what exaclty is happening here...??
Thanks
You can't change the value of constants, though you can take it's
address... and attempt to modify it via the pointer. The compiler does
const folding to reduce the value of expressions involving constants at
compile time, that's why you are seeing this behavior.

-
SJ

Jul 25 '06 #2
* co******@gmail. com:
>
Can anyone help me where exactly at what address the *p is storing the
updated value ( which is 99).

const int k=9;

int *p=(int *)&k;

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k

cout<<"Addreses \n"<<&(*p)<<& k; //BOTH the addresses are same.

cout<<"values \n"<<*p<<k; //But still the values are differentl.

what exaclty is happening here...??
Undefined Behavior (UB), because: modifying an originally const variable.

Or, practically speaking, that you have told the compiler that it can
rely on k being constant, so that it can use the original value directly
wherever it's needed. When you request the address of k you get the
address of a location containing that value. But that doesn't mean the
compiler needs to (generate code to) retrive the value from that
location where the value is used; you've explicitly told the compiler
that it doesn't need to, that the value is constant, unchanging.

However, formally none of that reasoning holds, because you have UB.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 25 '06 #3
co******@gmail. com wrote:
const int k=9;
^^^^^
int *p=(int *)&k;
*p=99; //here *p has updated the value of k
no, it has not. You previously declared that k won't change, marking it
const. What you actually do in above line is invoking undefined
behaviour - you misled the compiler, thus compiler is free to do
anything.
B.

Jul 25 '06 #4

co******@gmail. com wrote:
Hello Friends
Can anyone help me where exactly at what address the *p is storing the
updated value ( which is 99).

const int k=9;

int *p=(int *)&k;

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k

cout<<"Addreses \n"<<&(*p)<<& k; //BOTH the addresses are same.

cout<<"values \n"<<*p<<k; //But still the values are differentl.

what exaclty is happening here...??
Thanks
like above, you want to change the constant via a pointer which pointe
to it,I think it will work .
the k 's address are the same as p while the values are not, I think
the compiler maybe optimize the constants, like puting them in the
register. so try to add a votatile keywords in front of the definition
of k:
volatile const int k = 9; ///looks very funny
the result may be what you want ( I only test it in VC8.0 ) :-)

Jul 25 '06 #5
co******@gmail. com wrote:
Can anyone help me where exactly at what address the *p is storing the
updated value ( which is 99).

const int k=9;

int *p=(int *)&k;

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k
'k' is a constant object. Its value cannot be changed. An attempt to cast away
constness of 'k' and "change" its value (which is what you do above) will only
lead to undefined behavior. That's what happens in your case.

--
Best regards,
Andrey Tarasevich
Jul 25 '06 #6
co******@gmail. com posted:
const int k=9;

int *p=(int *)&k;

Equivalent to:

int *p = const_cast<int* >(&k);

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k

7.1.5.1/4:

Any attempt to modify a const object during its lifetime results in
undefined behavior.

cout<<"Addreses \n"<<&(*p)<<& k; //BOTH the addresses are same.

cout<<"values \n"<<*p<<k; //But still the values are differentl.

what exaclty is happening here...??

The beauty of undefined behaviour.

--

Frederick Gotham
Jul 25 '06 #7
co******@gmail. com wrote:
Hello Friends
Can anyone help me where exactly at what address the *p is storing the
updated value ( which is 99).

const int k=9;

int *p=(int *)&k;

cout<<"Addr of k : "<<&k<<" "<<p;

*p=99; //here *p has updated the value of k

cout<<"Addreses \n"<<&(*p)<<& k; //BOTH the addresses are same.

cout<<"values \n"<<*p<<k; //But still the values are differentl.

what exaclty is happening here...??
Thanks
Why do you call this "surprising problem"? You have broken the
restrictions on well-defined programs by telling the compiler a variable
is const and then changing it. Now it doesn't do what you expect it to.
Why do you expect any particular answer? The program has undefined
behaviour. That's that. Write programs that obey the standard and _then_
you have cause to query happenings outside what the standard predicts.
But here, even if anyone explains some mechanism that cause this result,
and even if you find some other kludge that makes it give the output you
want, what on earth makes you think that it will still give the output
you want if compiled by another compiler, or even by the same compiler
after a version upgrade? I mean, it's not rocket physics; you can guess
that this is undefined even without looking at the standard: you are
telling porkies to the compiler.

--
Ron House ho***@usq.edu.a u
http://www.sci.usq.edu.au/staff/house
Jul 27 '06 #8

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

Similar topics

117
7286
by: Peter Olcott | last post by:
www.halting-problem.com
28
5235
by: Jon Davis | last post by:
If I have a class with a virtual method, and a child class that overrides the virtual method, and then I create an instance of the child class AS A base class... BaseClass bc = new ChildClass(); .... and then call the virtual method, why is it that the base class's method is called instead of the overridden method? How do I fix this if I don't know at runtime what the child class is? I'm using Activator.CreateInstance() to load the...
12
1749
by: Jack | last post by:
Imagine if someone asked which of the follwing two methods of encoding an integer into a byte array was quicker. The purpose is in preparation for sending across a socket as part of a 'header'. If you are curious, run the code yourself. if(args.Length != 1)
2
1191
by: pavan | last post by:
See the following code : #include <iostream> using namespace std; float f1 = 1.0e+6; // This function just returns f1. float value1()
6
3822
by: Ammar | last post by:
Dear All, I'm facing a small problem. I have a portal web site, that contains articles, for each article, the end user can send a comment about the article. The problem is: I the comment length is more that 1249 bytes, then the progress bar of the browser will move too slow and then displaying that the page not found!!!! If the message is less than or equal to 1249 then no problem.
45
2970
by: charles.lobo | last post by:
Hi, I have recently begun using templates in C++ and have found it to be quite useful. However, hearing stories of code bloat and assorted problems I decided to write a couple of small programs to check. What I expected was that there would be minor code bloat and some speed improvement when using templates. However... I wrote a basic list container (using templates), and a list container (using virtual derived classes). I also tried...
4
5704
by: David Abrahams | last post by:
I'm seeing highly surprising (and different!) behaviors of PyImport_ImportModule on Linux and Windows when used in a program with python embedding. On Linux, when attempting to import a module xxx that's in the current directory, I get ImportError: No module named xxx I can work around the problem by setting
1
1080
by: =?Utf-8?B?bWljaGFlbCBzb3JlbnM=?= | last post by:
Linda: Thank you so much for explaining why my code was really working as it was supposed to; I understand now why the sequence of statements I originally used was flawed. And thanks also for specifying a better sequence of statements. Once I understood why you ordered them as you did and I changed my code to match, this also fixed another elusive bug I was encountering but had not yet had enough details to post a question about. (The bug...
10
5078
by: Juha Nieminen | last post by:
I suppose you can never know C++ fully. I would have never guessed this actually compiles and works: struct Point { int x, y; }; struct Line { Point endpoint; int weight; };
0
11164
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10767
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10864
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9588
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7137
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6008
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4623
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4230
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3242
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.