Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean? (int &)a

Tags:

c++

define a float variable a, convert a to float & and int &, what does this mean? After the converting , a is a reference of itself? And why the two result is different?

#include <iostream>
using namespace std;
int
main(void)
{
    float a = 1.0;
    cout << (float &)a <<endl;
    cout << (int &)a << endl;

    return 0;
}


thinkpad ~ # ./a.out 
1
1065353216
like image 768
Fei Xue Avatar asked May 10 '12 07:05

Fei Xue


1 Answers

cout << (float &)a <<endl;
cout << (int &)a << endl;

The first one treats the bits in a like it's a float. The second one treats the bits in a like it's an int. The bits for float 1.0 just happen to be the bits for integer 1065353216.

It's basically the equivalent of:

float a = 1.0;
int* b = (int*) &a;
cout << a << endl;
cout << *b << endl;

(int &) a casts a to a reference to an integer. In other words, an integer reference to a. (Which, as I said, treats the contents of a as an integer.)

Edit: I'm looking around now to see if this is valid. I suspect that it's not. It's depends on the type being less than or equal to the actual size.

like image 77
Corbin Avatar answered Oct 03 '22 09:10

Corbin