473,898 Members | 2,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

change a constant by pointer

#include <iostream>
using namespace std;

// Check if N is constant
template <int N>
class ValidateConstIn t{};

int main()
{
const int constValue = 12;
const int* pConstValue = &constValue;
int* pValue = const_cast <int*( &constValue );

ValidateConstIn t <constValue() ; // Check if constValue is
constant

cout << "------------------------------------ " << endl;
cout << " begin: " << endl;
cout << "\t const int constValue = 12; " << endl;
cout << "\t const int* pConstValue = &constValue; "<< endl;
cout << "\t int* pValue = const_cast <int*(&ConstVal ue);"<<
endl;
cout << endl;

cout << "------------------------------------ " << endl;
cout << " constValue = " << constValue << endl;
cout << " &constValue = " << &constValue << endl;
cout << " *pConstValue = " << *pConstValue << endl;
cout << " pConstValue = " << pConstValue << endl;
cout << " *pValue = " << *pValue << endl;
cout << " pValue = " << pValue << endl;
cout << endl;

*pValue = 1; // Change the value

cout << "------------------------------------- After *pValue = 1
" << endl;
cout << endl;

cout << " constValue = " << constValue << endl;
cout << " &constValue = " << &constValue << endl;
cout << " *pConstValue = " << *pConstValue << endl;
cout << " pConstValue = " << pConstValue << endl;
cout << " *pValue = " << *pValue << endl;
cout << " pValue = " << pValue << endl;
cout << "------------------------------------ " << endl;
return 0;
}

// ------------- Result:
------------------------------------
begin:
const int constValue = 12;
const int* pConstValue = &constValue;
int* pValue = const_cast <int*(&ConstVal ue);

------------------------------------
constValue = 12
&constValue = 0012FF6C
*pConstValue = 12
pConstValue = 0012FF6C
*pValue = 12
pValue = 0012FF6C

------------------------------------- After *pValue = 1

constValue = 12 // not changed
&constValue = 0012FF6C
*pConstValue = 1 // have changed
pConstValue = 0012FF6C
*pValue = 1 // have changed
pValue = 0012FF6C
------------------------------------

The pConstValue and pValue both point to the ConstValue, and the value
access by the point is changed, but constValue has never changed ( and
it shoule not be a constant ). I can not explain, Can somebody help
me ?
Nov 8 '08 #1
8 2014
I try the next:

....
int main()
{
int x = 12;
* * *const int *constValue *= X;
* * *const int* pConstValue = &constValue;
* * *int* * * * pValue * * *= const_cast <int*( &constValue );
....

And get compiler error:
'ValidateConstI nt' : template parameter 'N' : 'constValue' : a local
variable cannot be used as a non-type argument

Perhaps in your case compiler doesn't create constValue, it just uses
its value: 12 (kind of optimization). So you get such a result. By I'm
not shure.
Nov 8 '08 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

want.to.be.prof esser wrote:
<snip>
The pConstValue and pValue both point to the ConstValue, and the value
access by the point is changed, but constValue has never changed ( and
it shoule not be a constant ). I can not explain, Can somebody help
me ?
According to paragraph 7.1.5.1/4:
"(...) any attempt to modify a const object during its lifetime results
in undefined behavior."
That's why you get that. In fact you compiler optimized constValue, and
put its value to the parts where it was directly used. In other cases
(referencing to constValue through pointers) it was treated as a pointer
to non-cv-qualified object.

Pawel Dziepak
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iEYEARECAAYFAkk VhjwACgkQPFW+cU iIHNq59ACdGcVJE cVFYYpUeGbAJ/hEwYMn
7QgAnR2pxba7gWy 4eQHDnTKPfTBe8u TI
=fRhq
-----END PGP SIGNATURE-----
Nov 8 '08 #3
On 11月8日, 下午8时13分, maverik <maverik.m...@g mail.comwrote:
I try the next:

...int main()
{

int x = 12; const int constValue = X;
const int* pConstValue = &constValue;
int* pValue = const_cast <int*( &constValue );

...

And get compiler error:
'ValidateConstI nt' : template parameter 'N' : 'constValue' : a local
variable cannot be used as a non-type argument

Perhaps in your case compiler doesn't create constValue, it just uses
its value: 12 (kind of optimization). So you get such a result. By I'm
not shure.
In my windows XP OS, I used vs2005 and g++ compiler.They both like
this.
Nov 8 '08 #4
On 2008-11-08 12:52, want.to.be.prof esser wrote:
#include <iostream>
using namespace std;

// Check if N is constant
template <int N>
class ValidateConstIn t{};

int main()
{
const int constValue = 12;
const int* pConstValue = &constValue;
int* pValue = const_cast <int*( &constValue );

ValidateConstIn t <constValue() ; // Check if constValue is
constant

cout << "------------------------------------ " << endl;
cout << " begin: " << endl;
cout << "\t const int constValue = 12; " << endl;
cout << "\t const int* pConstValue = &constValue; "<< endl;
cout << "\t int* pValue = const_cast <int*(&ConstVal ue);"<<
endl;
cout << endl;

cout << "------------------------------------ " << endl;
cout << " constValue = " << constValue << endl;
cout << " &constValue = " << &constValue << endl;
cout << " *pConstValue = " << *pConstValue << endl;
cout << " pConstValue = " << pConstValue << endl;
cout << " *pValue = " << *pValue << endl;
cout << " pValue = " << pValue << endl;
cout << endl;

*pValue = 1; // Change the value

cout << "------------------------------------- After *pValue = 1
" << endl;
cout << endl;

cout << " constValue = " << constValue << endl;
cout << " &constValue = " << &constValue << endl;
cout << " *pConstValue = " << *pConstValue << endl;
cout << " pConstValue = " << pConstValue << endl;
cout << " *pValue = " << *pValue << endl;
cout << " pValue = " << pValue << endl;
cout << "------------------------------------ " << endl;
return 0;
}

// ------------- Result:
------------------------------------
begin:
const int constValue = 12;
const int* pConstValue = &constValue;
int* pValue = const_cast <int*(&ConstVal ue);

------------------------------------
constValue = 12
&constValue = 0012FF6C
*pConstValue = 12
pConstValue = 0012FF6C
*pValue = 12
pValue = 0012FF6C

------------------------------------- After *pValue = 1

constValue = 12 // not changed
&constValue = 0012FF6C
*pConstValue = 1 // have changed
pConstValue = 0012FF6C
*pValue = 1 // have changed
pValue = 0012FF6C
------------------------------------

The pConstValue and pValue both point to the ConstValue, and the value
access by the point is changed, but constValue has never changed ( and
it shoule not be a constant ). I can not explain, Can somebody help
me ?
One of the reasons we have constants is that they allow for certain
optimisations. Since the compiler knows the value of constValue it can
skip a lot of stuff it would have to do if it was a variable. If you had
not taken its address the compiler would probably not allocated the
memory for it at all and used the value of 12 wherever constValue was
used. But since you took the its address it had to allocate some memory
for it, but since it knew it was constant it still didn't bother to use
it and did the optimisations anyway.

Notice also that what you did (taking the address of a constant, casting
away the const-ness and using the pointer to change the value) is not
allowed, and with other settings / compiler / OS your program would have
crashed instead because constValue would have been places in read only
memory. In sort, if you do not follow the rules of the languages
anything can happen and no guarantees are given.

--
Erik Wikstr枚m
Nov 8 '08 #5
want.to.be.prof esse wrote:
#include <iostream>
using namespace std;

// Check if N is constant
template <int N>
class ValidateConstIn t{};

int main()
{
const int constValue = 12;
const int* pConstValue = &constValue;
int* pValue = const_cast <int*( &constValue );
Any attempt to modify what pValue points to is undefined behavior, since
it points to a const object.

[...]
*pValue = 1; // Change the value
This invokes undefined behavior. Game over.
[...]
The pConstValue and pValue both point to the ConstValue, and the value
access by the point is changed, but constValue has never changed ( and
it shoule not be a constant ). I can not explain, Can somebody help
me ?
Nov 8 '08 #6
Notice also that what you did (taking the address of a constant, casting
away the const-ness and using the pointer to change the value) is not
allowed, and with other settings / compiler / OS your program would have
crashed instead because constValue would have been places in read only
memory.
Proof:

write

static const int constValue = 12;

instead of

const int constValue = 12;

The program crashes in this case (WinXP SP1, VC8.0) with exception
that says that I try to write to readonly memory
Nov 8 '08 #7
The pConstValue and pValue both point to the ConstValue, and the value
access by the point is changed, but constValue has never changed ( and
it shoule not be a constant ). I can not explain, Can somebody help
me ?
You're confusing what "const" means... Const means "you cannot change
it" and does NOT mean that "it cannot be changed" (your program is an
example of this!). Change these declarations from "const" to "volatile
const" and your program will work the way you had hoped (constValue
returns 1 after *pValue is altered):
volatile const int constValue = 12;
volatile const int* pConstValue = &constValue;
Nov 9 '08 #8
On Nov 9, 4:40 pm, JaredGrubb <jared.gr...@gm ail.comwrote:
The pConstValue and pValue both point to the ConstValue, and
the value access by the point is changed, but constValue has
never changed ( and it shoule not be a constant ). I can not
explain, Can somebody help me ?
You're confusing what "const" means... Const means "you cannot
change it" and does NOT mean that "it cannot be changed" (your
program is an example of this!).
It depends. Const has two meanings. In general, you cannot
modify a value throw an expression which refers to an object (an
lvalue expression, in standardese) and has a const type; you can
modify the object through other expressions, however. If the
object itself is const, however (as is the case here), any
attempt to modify it is undefined behavior.
Change these declarations from "const" to "volatile const" and
your program will work the way you had hoped (constValue
returns 1 after *pValue is altered):
It might, or it might not. Undefined behavior is undefined
behavior.
volatile const int constValue = 12;
volatile const int* pConstValue = &constValue;
The volatile simply tells the compiler that this object might be
modified by something outside the program. Any attempt to
modify it from within the program is still undefined behavior.
As another poster pointed out, declaring the object static could
very well end up in the attempt to modify it causes a core dump.
The volatile probably won't help here.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orient閑 objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place S閙ard, 78210 St.-Cyr-l'蒫ole, France, +33 (0)1 30 23 00 34
Nov 10 '08 #9

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

Similar topics

1
10011
by: Kent | last post by:
Hi! I am working with an obscure graphics library in school as a university C++ programming project. The graphics library has a class kalled Bitmap wich you use to draw graphics (you can "stamp it down" on the screen, double buffering and such is all within the lib). This is how it works now (i think its a bad design): In a class i created to represent "monsters" in a game i have the following
4
1952
by: Fraser Ross | last post by:
Are these pointers the same? Fraser.
6
1858
by: amparikh | last post by:
I know this is something fundamental and I ought to have known it, but somehow this seems to be confusing me a lot. Fundamentally, rvalues and/or temporaries can be bound only to constant references going by the const guidelines. Taking that into consideration, how does one get a constant reference to a pointer. class A
11
2389
by: Mantorok Redgormor | last post by:
Is const really constant? And on an OT note: how can I post with a modified e-mail address so I don't get so much spam?
7
4939
by: Thomas L. | last post by:
Hi all, Does a "NULL constant function" exist in C? I mean: I am searching for a C language constant which would be something like a function but which would be translated by a compiler into "nothing": no argument push in the stack pointer, no execution of the function instructions, no cleaning up, nothing, nada, rien, vide... I could then initialize a function pointer f to that constant function and ask (*f)(any_argument_list)
4
2197
by: sam_cit | last post by:
Hi Everyone, I understand the meaning and usage of pointers to constant characters and constant pointers to characters, however i often get confused with the syntax of expressing them, can anyone help me out with few examples?
3
2355
by: Old Wolf | last post by:
The code is: extern int x; char *ptr1 = 8 + (char *)&x; char *ptr2 = (char *)(8 + (unsigned)&x); My understanding is that the ptr1 declaration is correct but the ptr2 is not, and the compiler can reject it (even if the compiler has a meaningful definition of integer<->pointer conversions).
45
18948
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
7
2823
by: John Koleszar | last post by:
Hi all, I'm porting some code that provides compile-time assertions from one compiler to another and ran across what I believe to be compliant code that won't compile using the new compiler. Not naming names here to remove bias - I'm trying to tell if I'm relying on implementation defined behavior or if this is a bug in the new compiler. Consider this stripped down example:
0
9839
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11254
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
10854
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...
0
10480
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8034
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7187
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
5876
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6076
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3303
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.