float b = 1.0f;
int i = (int)b;
int& j = (int&)b;
cout << i << endl;
cout << j << end;
Then the output of i was 1, and the output of j was 1065353216! It is a big surprise to me! So what is the true meaning of (int&) conversion?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is the problem with a C-style cast. You have to look closely to see what you’re getting. In your case “(int)” was a normal static cast. The value is converted to an int via truncation. In your case “(int&)” was a reinterpret cast. The result is an lvalue that refers to the memory location of b but is treated as an int. It’s actually a violation of the strict aliasing rules. So, don’t be surprized if your code won’t work anymore after turning on all optimizations.
Equivalent code with C++ style casts:
Check your favorite C++ book on these kinds of casts.