Re: conversion from float to int&
* liujiaping:
The code is as follows:
1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 float a = 1.0f;
8 cout << (int)a << endl;
9 cout << (int&)a << endl;
10 cout << boolalpha << ( (int)a == (int&)a ) << endl;
11 float b = 0.0f;
12 cout << (int)b << endl;
13 cout << (int&)b << endl;
14 cout << boolalpha << ( (int)b == (int&)b ) << endl;
15 return 0;
16 }
The program output is:
1
1065353216
false
0
0
true
I am wondering why line 9 prints 1065353216, while line 13 prints 0.
Don't wonder about that, just stay away from it.
Can anybody explains this?
"(int&)a" is equivalent to "*reinterpret_cast<int*>(&a)". In other
words, you're accessing the bits of a float is if they represented an
int. The result is highly system-dependent.
However, in general, most likely a C++ implementation will use IEEE
format for floats, where a 0 is represented as all zero bits.
And what will happen if I convert a variable of type float to a
variable of type int&?
There is no such thing as a variable of type int&. References are not
objects. The variable is of type int.
For your own good, just DON'T USE CASTS.
If you absolutely need to use a cast, absolutely don't use C-style casts
(like you do above), but instead one or more of dynamic_cast,
const_cast, static_cast, and reinterpret_cast. That way you can search
for casts in your code, see the what the indended effect is, and perhaps
even understand more when your compiler complains.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?