views:

173

answers:

5

In C++, the following lines have me confused:

int temp = (int)(0×00);

int temp = (0×00int);

What is the difference between those 2 lines?

+11  A: 

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;
Mark Byers
To clarify a bit more, the second statement tells the compiler that you want to assign "temp" some value. Using the "0x" prefix tells it that this value is going to be expressed in HexaDecimal. Valid characters for hexadecimal number are: 1234567890abcdef. Now you must see the problem in your statement.
Poni
+1  A: 

The first will assign 0 to temp

Second will result in compilation error.

When the scanner sees 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.

codaddict
+1  A: 

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.

Daniel Daranas
A: 

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).

The Elite Gentleman
+3  A: 

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".

MadKeithV