Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with keyword const

Status
Not open for further replies.

kai2005

Programmer
Oct 8, 2005
21
DE
please take a look of this program, how can this be explained?

Code:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
  const int i=0;
  int * j=(int*)&i;  
  const int k=0;
  int * u=(int*)&k;
  *j+=1;
  *u+=1;
  cout<<i<<"   "<<*j<<endl;
  cout<<&i<<" "<<j<<endl;
  cout<<k<<"   "<<*u<<endl;
  cout<<&k<<" "<<u<<endl;
  system("pause");
  return 0;
}
 
C++ Std said:
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:
--- a long list w/o (cast-expression const ptr => ptr) ---
So
Code:
const int k;
int * u=(int*)&k;
is semantically legal sequence until you try to modify k via *u. There are program cases where it's necessary (or useful) to get not-const pointer to a const object (especially in legacy codes).
Yes, it's a nasty taste but it's not an interesting case.
The language can't (and should not) prevent all programmer's errors. Remember the most reliable aircraft with ferro-concrete wings...
Moreover, the implementation can place k var in read-only storage (but should not to do that).
Well, let's see:
Code:
int a[2];
f(a);
....
void f(int a[])
{
... 
  a[2] = 0;
...
Oh, what's a terrible language defect, place a ban on array indexing!...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top