473,387 Members | 1,834 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,387 software developers and data experts.

pointer to const in c++

I wrote a program like this(test.cpp)
and the result is
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pointer to a =2
const a =1
address of a 0xbfffdd44
address of p 0xbfffdd44
~~~~~~~~~~~~~~~~~~~~~~~~~~~
what on earth the value is in (0xbfffdd44)? Thank you
#include <iostream>
using namespace std;
int main()
{
const int a = 1;
int* p;
p = (int*)&a;
(*p)++;
cout<< "pointer to a ="<<*p<<endl;
cout<< "const a =" << a<< endl;
cout<< "address of a" <<&a<<endl;
cout<< "address of p" <<p<<endl;
return 0;
}

Jul 19 '05 #1
3 1880

"Sean Yang" <ya****@purdue.edu> wrote in message news:3F************@purdue.edu...
what on earth the value is in (0xbfffdd44)? Thank you


Impossible to tell. You have undefined behavior in that you
changed an object defined as const through your cast. This
is an extremely bad thing to do. The standard puts no constraints
on what might happen.
Jul 19 '05 #2
Sean Yang wrote:
I wrote a program like this(test.cpp)


Please don't send attachments to text groups. There are a number of good
reasons for this, two important ones being 1) people don't trust
attachments and won't open them, and 2) some news servers refuse
messages with attachments so some people will never see the message at all.

Put your code in the body of the message.

http://www.parashift.com/c++-faq-lit...t.html#faq-5.4
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #3
Sean Yang wrote:
I wrote a program like this(test.cpp)
and the result is
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pointer to a =2
const a =1
address of a 0xbfffdd44
address of p 0xbfffdd44
~~~~~~~~~~~~~~~~~~~~~~~~~~~
what on earth the value is in (0xbfffdd44)? Thank you


This is undefined behaviour, but my bet is on 2.

I ran this code through Visual C++ .Net 2003, and what happened is this:
When you do cout << *p, the value of *p gets pushed on the stack like this:
0041B1ED mov eax,dword ptr [p]
0041B1F0 mov ecx,dword ptr [eax]
0041B1F2 push ecx
When you do cout << a, the value of a gets pushed on the stack like this:
0041B218 push 1

Because a is a constant, the actual 'read a' part is optimised away and 1 is
just inserted into the program where it should've been.
*P is computed, so at memory location p, which is the same as &a, you'll
find the value 2. But this is never read when using a, because that's
optimised away. This is such a basic optimisation that VC even does it when
optimisation is turned *off*!

The story becomes a little different when you use optimisations though.
Because you only use constants, the value of *p is also precomputed at
compile time, so print it becomes a 'push 2'. Because it's not needed, it's
never put in memory, so what's actually in the memory location is whatever
was there before your program started, there's no way to tell. In fact, the
only reason there still is memory allocated on the stack for a and p is
because you request their addresses. If you hadn't the variables would
probably have been optimised out of the program completely.

Note that this whole story is *very* implementation dependant. A compiler is
free to give warnings or errors about what you're trying to do. If a
compiler decides to put the constant in a write-protected segment of memory
the program would crash.

Bottom-line: don't do it! Also, try using C++ casts. Both
static_cast<int*>(&a) and reinterpret_cast<int*>(&a) woud've given you an
error (at least in VC.NET 2003):
cpptest.cpp(7) : error C2440: 'reinterpret_cast' : cannot convert from
'const int *__w64 ' to 'int *'
Conversion loses qualifiers

You should always use C++ casts, because as this example demonstrates, with
C-style casts you just can't be sure it does what you expect it to do. Right
now you're C-style cast acts equivalent to a const_cast, and as the
documentation so rightly notices about const_cast:
"Depending on the type of the referenced object, a write operation through
the resulting pointer, reference, or pointer to data member might produce
undefined behavior."

--
Unforgiven

"Most people make generalisations"
Freek de Jonge

Jul 19 '05 #4

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

Similar topics

10
by: Chris Mantoulidis | last post by:
I see some really weird output from this program (compiled with GCC 3.3.2 under Linux). #include <iostream> using namespace std; int main() { char *s; s = "test1"; cout << "s = " << s << "...
10
by: quantdev2004 | last post by:
Hi all, I have been deling with this kind of code: class Foo { public: void NonConstMethod() {} };
5
by: Danilo Kempf | last post by:
Folks, maybe one of you could be of help with this question: I've got a relatively portable application which I'm extending with a plugin interface. While portability (from a C perspective) is...
204
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 =...
18
by: hzmonte | last post by:
typedef int t_compare_func(const void *, const void *); struct node *tree_search(struct node *root, const void *keyy, t_compare_func *comp) { struct node *cur_item; int result; if (root ==...
21
by: Roman Werpachowski | last post by:
I can't understand this: double * x = new double; const double * p = x; delete p; works. Why am I allowed to delete a const pointer? On the same note: why am I allowed to do this: class...
5
by: max | last post by:
Dear all, I did the following analysis to conclude that the following pointer types are not compatible. Please let me know If my analysis and interpretation of the C standard are correct: ...
1
by: Tomás | last post by:
Some programmers treat arrays just like pointers (and some even think that they're exactly equivalent). I'm going to demonstrate the differences. Firstly, let's assume that we're working on a...
29
by: shuisheng | last post by:
Dear All, The problem of choosing pointer or reference is always confusing me. Would you please give me some suggestion on it. I appreciate your kind help. For example, I'd like to convert a...
2
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...

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.