Casting pointers that do not produce the expected result

Possible duplicate:
C / C ++ constant value change

The following program:

int main()
{
    const int x = 10;
    int * p = (int *)&x;
    *p = 12;
    cout<<x<<endl;
    cout<<*p<<endl;
    return 0;
}

Gives output:

10
12

What is the effect of casting & x to (int *) and why is the value of x still 10? I expected it to be 12.

Another doubt

Why can't we say int ** int int const? Rather, this operation is really

void f(int const ** p);
void g(int const * const * p);

int main()
{
    int ** p = /*....*/
    f(p);   //Error
    g(p);   //OK
}

Please help me figure this out with a suitable example. Thanks !!!

+3
source share
4 answers

You invoke undefined behavior by modifying a variable declared as const. Any result is a legitimate exit from the program, although some results are more believable than others.

As I noticed in the comment:

10 ; , x const, :

cout << 10 << endl;

:

cout << x << endl;

, :

cout << 12 << endl;

, . undefined, , , .

+8

, const int. :

        cout<<10<<endl;
        cout<<*p<<endl;
+2

: - undefined.

, , const-correctness:

const int k = 10;
void f(int const ** p) {
    *p = &k;                   // Valid, p promises not to change k
}
void g(int const * const * p);

int main()
{
    int *p;
    int ** pp = &p;
    f(pp);                     // If allowed: p points to k!!!
    p = 5;                     // Modifying a constant object!!!
    g(pp);                     //OK
}

In the case g, since the signature of the function promises that the intermediate pointer will not be changed, the compiler knows that git will not change *pp, which means that it cannot do *pp(i.e. p) points to a constant object, and const-correctness is guaranteed.

+1
source

well, this is an interesting question. when you remove the const x prefix, you will get the result as you wish.

int main()       
{               
 int x = 10;               
 int * p = (int *)&x;               
 *p = 12;              
 cout<<x<<endl;              
 cout<<*p<<endl;               
 return 0;      
}

I think this is a constant label preventing the x value from changing.

0
source

All Articles