Link to home
Start Free TrialLog in
Avatar of dennis_george
dennis_georgeFlag for India

asked on

Optimization of const variable.....

Hi all,

I have a small test file.....

int main()
{
   const int iValue = 10 ;

   int *ptr = const_cast<int *> &iValue ;

   *ptr = 20 ;

   cout << "Address :: " << &iValue << ", " << ptr << endl ;
   cout << "Value     :: " << iValue   << ", " << *ptr << endl ;

   return 0 ;
}

I have defined a const int with value 10.... and removed its const property using const_cast and modified its value..... But when you print their values.... they differ... even though their addresses are same...... Even though morally you shouldn't do such things.....  But I am wondering how this can be possible......

So I checked the Assembly output of the program And I got the answer..... compiler replaced all the instances  of iValue with 10 directly without refering to the actual memory location of iValue.......

So I concluded this is some sort of optimization.... First of all I want to ask whether I am correct or not... if yes how can I stop the compiler to stop the optimization....

thanks in advance
Dennis
Avatar of jkr
jkr
Flag of Germany image

>>But when you print their values.... they differ...

Are you using VC++? This one sets up 'const' variables in a different data segment, sicnce

int main()
{
  int iValue = 10 ;

  int *ptr = const_cast<int*>( &iValue) ;

  *ptr = 20 ;

  cout << "Address :: " << &iValue << ", " << ptr << endl ;
  cout << "Value     :: " << iValue   << ", " << *ptr << endl ;

  return 0 ;
}

produces the desired results. This seems to be a compiler bug.

SOLUTION
Avatar of efn
efn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dennis_george

ASKER

I am working on g++ (gcc)....

The actual memory location is getting changed but iValue is not reflected properly.... Tje result is still the same.... Ya the bracket is required for error free compilation (I missed it.... in my example)

I think VC++ also gives the same result even though I haven't tested it....

Dennis
I think in compiler you can specify various optimization level... like O3, O2, etc.... so you mean to say that there is no way to avoid this optimization

Dennis
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ya,

>>Consider what would happen if you could change the value in the following code:
>>
>>const int x = 3;
>>char data[x];

I think you are correct....... It shouldn't be changed......  

Dennis