Ampersand Inside Casting

I come across this code

int n1 = 10;
int n2 = (int &)n1;

I do not understand the meaning of this casting, n2 is not a link, since the modification of n1 does not reflect n1. Oddly, this code generates a compiler error in gcc, where it compiles in VC ++.

Does anyone know the meaning of this caste?

+5
source share
6 answers

Assuming it n2has some kind of built-in type, the cast to type int &re-interprets the lvalue n1(any type that it had) as the lvalue of the type int.

int n2 = (int &) n1, n1 lvalue int, , . n1 - const int, , . n1 lvalue - , cast , n1 int ( punning). n1 l, .

, int n2 = (int&) n1 int & ( ), , .. n1 l - ( int).

float n1 = 5.0;
int n2 = (int &) n1;

int n2 = *(int *) &n1;

int n2 = *reinterpret_cast<int *>(&n1);

, .

BTW, , ++- . reinterpret_cast C-, , , .

, n1 int, . .

P.S. , n2 int &, -. , , n2, .

+9

++ g++ 4.4.1. n1, , , n2.

, :

void f( int & n1 ) {
   int n2 = n1;   // initialise with valuue referred to by n1
}

, C, C .

+11
int main()
{
        int n1 = 10;
        int n2 = (int &)n1;
        cout<<n2<<endl;
}

10, .
.
, :

int main()
{
        int n1 = 10;
        int n2 = (int &)n1;
        n2 = 20;
        cout<<n1<<endl; // print 10 and not 20.
}
+2

, , , .

GCC , V++. , . temp n1, n2.

+1

This does the obvious thing. Paste n1int into the link, and then assign it int n2.

And assuming it n1is an int, it should compile just fine.

It will not compile if n1is the value of r. The following will not compile, for example:

(int&)foo();
(int&)42;
(int&) (x+y); // assuming x and y are int variables
+1
source

It compiles to gcc too (I tried to just make sure). It just passes n1 to the link.

0
source

All Articles