Why this const variable is not changing even after applying const_cast?


 
Thread Tools Search this Thread
Top Forums Programming Why this const variable is not changing even after applying const_cast?
# 1  
Old 04-28-2011
Why this const variable is not changing even after applying const_cast?

Hi

In the following code, why the variable 'i' still retains the value 10 instead of 11? Why it is not possible to alter this variable's value?
Code:
int main() {
    const int i = 10;
    *(const_cast<int*>(&i)) = 11;
    cout << i << endl;  // Ans: 10
}

# 2  
Old 04-28-2011
Quote:
Originally Posted by royalibrahim
Hi

In the following code, why the variable 'i' still retains the value 10 instead of 11? Why it is not possible to alter this variable's value?
Code:
int main() {
    const int i = 10;
    *(const_cast<int*>(&i)) = 11;
    cout << i << endl;  // Ans: 10
}

What makes you think it should change a "constant"...i is a constant and the pointer is to a constant which shouldnt change i.
# 3  
Old 04-28-2011
Unless I am mistaken, modifying any object that was actually defined as const leads to an undefined behavior (which 10 at the end might indeed result).

I checked on Gnu/Linux : it seems that g++ simply replace i by the value of 10 during compilation (even tough it computes 11), as we can verify on the produced assembler code:

Code:
main:
.LFB957:
   .cfi_startproc
   .cfi_personality 0x3,__gxx_personality_v0
   pushq %rbp
   .cfi_def_cfa_offset 16
   movq  %rsp, %rbp
   .cfi_offset 6, -16
   .cfi_def_cfa_register 6
   subq  $16, %rsp
   movl  $10, -4(%rbp)
   leaq  -4(%rbp), %rax
   movl  $11, (%rax)            # here it is 11 
   movl  $10, %esi              # but 10 is used for cout
   movl  $_ZSt4cout, %edi
   call  _ZNSolsEi
   movl  $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_, %esi
   movq  %rax, %rdi
   call  _ZNSolsEPFRSoS_E
   movl  $0, %eax
   leave
   ret
   .cfi_endproc

To verify this claim, it had the weird idea to qualify the const int i variable as volatile (why on the earth would we need to always re-read a const value from memory?). And tata: I got then 11.

Obviously, this is highly compiler/system depends. So the bottom line is: don't do that.

Cheers, Loïc
# 4  
Old 04-29-2011
Quote:
Originally Posted by shamrock
What makes you think it should change a "constant"...i is a constant and the pointer is to a constant which shouldnt change i.
When I access it through a pointer after suppressing const'ness, I could change the value through the pointer, but still 'i' remains the same, (i.e)

Code:
int main() {
    const int i = 10;
    int *p = const_cast <int*> (&i);
    *p = 11;
    cout << *p << "  " << i << endl;  // Ans: 11  10

    *(const_cast<int*>(&i)) = 11;
    cout << i << endl;  // Ans: 10

    *(const_cast<int*>(p)) = 12;
    cout << *p << "  " << i << endl;  // Ans: 12  10
}

I compiled the above code using gcc compiler. What is really confusing me is, where the pointer '*p' is pointing to so that it is printing the value that is not stored in 'i'?
# 5  
Old 04-29-2011
I answered your question previously:
- the value at the memory location gets changed.
- when the compiler sees the variable "i", it replaces it directly by "10" (it's OK to do so, since it is a const, it is not supposed to change).

You found a good example to illustrate this undefined behavior.

Cheers, Loïc
This User Gave Thanks to Loic Domaigne For This Post:
# 6  
Old 05-03-2011
It's not unheard of for a compiler to do this even for non-constant variables, if it's convinced that nothing in the code ever touches the var. Things like:

Code:
static int debug_if=0; // Poke this value with your debugger when you want debug into to appear

...

if(debug_if) // ...but at high optimization, it might skip this anyway!
{
        fprintf("debug dump follows: ...\n");
        ...
}

# 7  
Old 05-03-2011
Quote:
It's not unheard of for a compiler to do this even for non-constant variables
Yes, that's one of the major trouble when doing embedded device programming. For instance, you're mapping a hardware register. Your compiler has absolutely no chance to guess that the variable used for this - though not modified by your code - can be actually be changed by the HW. So you need to tell the compiler explicitly about this fact using volatile.

Thinking a bit more, I believe that "const volatile" has a raison d'être, at least for embedded code. You're just saying: "my program isn't supposed to modify this variable" but "this variable can be changed by external source, like HW".

Thanks Corona for your point!
Cheers, Loïc
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Applying sed against a file from a list of values stored in a variable

Hi Forum. I have the following challenge at work that I need to write a script for. I have a file abc.txt with the following contents: 4560123456 4570987654 4580654321 I want to be able to search/replace in abc.txt - the first 4 characters anything starting with 4560 to 7777; 4570... (3 Replies)
Discussion started by: pchang
3 Replies

2. UNIX for Dummies Questions & Answers

Changing Path Variable

Blank Blank Blank (11 Replies)
Discussion started by: pvibien
11 Replies

3. UNIX for Dummies Questions & Answers

Getting input and changing variable?

Hi I am new to scripting and have a function in my .sh script file that outputs a html radio button form weather_forecast_config() { echo "" echo "<html><head><title>Welcome</title></head>" echo "<body>" echo "<h2>Weather Forecast - Change City</h2>" echo "<form name="input"... (5 Replies)
Discussion started by: scriptnewbie
5 Replies

4. Shell Programming and Scripting

Changing the variable using awk?

Dear all, I have kind of used both the awk/sed command and found them really useful. But at the necessity I am having right now, I need help. Actually, I would like to do the following in file script.sh PATH535="/eos/uscms/store/user/pooja04//analysis2012/535/mc/summer12/002/tt/" ... (2 Replies)
Discussion started by: emily
2 Replies

5. Shell Programming and Scripting

Changing variable name in for loop

Hi All please help if possible. I am a Unix novice. I have a similar question to the one posted by yonderboy at about a year ago. However his solution does not work for me. The pseudo code for my problem is as follows: for fund in 1 2 3 4 if (FTP is successfully) then FILE_SENT_fund... (2 Replies)
Discussion started by: Seether
2 Replies

6. Programming

C++ program is crashing on re-assigning const static member variable using an int pointer

Hi, Can any one tell me why my following program is crashing? #include <iostream> using namespace std; class CA { public: const static int i; }; const int CA::i = 10; int main() { int* pi = const_cast<int*>(&CA::i); *pi = 9; cout << CA::i << endl; } (6 Replies)
Discussion started by: royalibrahim
6 Replies

7. Programming

const_cast confusion

See code below. It appears that i and j inhabit the same address yet hold different values. Can anyone shed light on this? int main() { const int i= 3; int* j = const_cast<int*>(&i); *j = 5; cout << j << endl << &i << endl; cout << *j << endl << i; } (4 Replies)
Discussion started by: StuartH
4 Replies

8. Programming

C++ type-casting a member variable in const methods

Is it permitted to type-cast a member variable passed in as a parameter in a member const method .. I am doing something like : in a return-type method () const { variable other = long(member variable) } this other assigned variable is not updating and I wonder if type-casting in such... (1 Reply)
Discussion started by: shriyer123
1 Replies

9. Shell Programming and Scripting

Changing a variable Question

I have a variable: $FILENAME = /XXXX/XXXX/XXXX/file.dat I want to set another variable that will give me this: $FILENAME2=filea.dat So basically i'm chopping up variable $FILENAME. Not sure cut will do this as i'm looking at different directories so the characther length may be... (2 Replies)
Discussion started by: Pablo_beezo
2 Replies

10. Shell Programming and Scripting

IFS changing the variable value

Hi, I have a while read loop that reads files in a directory and process. The files have spaces in between, so I have the IFS=\n to to read the whole line as one file name. The read works fine but I have a problem with another variable that I set in the beginning of the script. The variable... (1 Reply)
Discussion started by: pvar
1 Replies
Login or Register to Ask a Question