Confused about type conversion in C++
In C++, the following lines have me confus开发者_C百科ed:
int temp = (int)(0×00);
int temp = (0×00int);
What is the difference between those 2 lines?
Both are invalid because you are using ×
instead of x
:
test.cpp:6: error: stray '\215' in program
test.cpp:6: error: expected primary-expression before "int"
test.cpp:6: error: expected `)' before "int"
But even fixing that, the second still isn't valid C++ because you can't write 0x00int
:
test.cpp:6:13: invalid suffix "int" on integer constant
The first is valid (after changing ×
to x
) and assigns the value 0 to temp. The cast is unnecessary here though - you don't need a cast just because the constant is written in hexadecimal. You can just write:
int temp = 0x00;
Ways to cast:
int temp = (int)0x00; // Standard C-style cast
int temp = int(0x00); // Function-style cast
int temp = static_cast<int>(0x00); // C++ style cast, which is clearer and safer
int temp = reinterpret_cast<int>("Zero"); // Big-red-flag style unsafe cast
The fun thing about static_cast and reinterpret_cast is that a good compiler will warn you when you're using them wrong, at least in some scenarios.
Visual Studio 2005 for example will throw an error if you try to reinterpret_cast 0x00 to an int, because that conversion is available in a safe way. The actual message is: "Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast".
The first will assign 0
to temp
Second will result in compilation error.
When the scanner sees 0×
it expects it to be followed with hexadecimal digit(s), but when it sees i
which is not a valid hex digit it gives error.
The first one takes the hex value 0x00 as an int, and uses it to initialize the variable temp.
The second one is a compile error.
First line is a valid C++, which basically equate to
int temp = 0;
while the second one will fail to compile (as suggested by everyone here).
精彩评论