Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's up with static_cast with multiple arguments?

Can anyone tell me what this cast has for effect (besides setting happyNumber to 1337), if any at all, and if it has no other effect, how come I can write code like this??? Is this a compiler bug, or some "hidden away feature" of C++?

int happyNumber = static_cast<int>(123.456, TRUE, "WTF" , false , "IS" , NULL , "GOING" , 0xff , "ON???" , 1337);

I was surprised this would compile at all. I found it through a bug where I accidentally set the second parameter to something that was meant to go in a function call of the expression being cast. This resulted in a nasty bug where the object was cast from the second parameter, calling the function with only one argument. It compiled... And didn't initially boom...

I am using Microsoft Visual C++ 2008.

like image 450
Statement Avatar asked Feb 27 '09 09:02

Statement


People also ask

Can static_cast fail?

static_cast can't throw exception since static_cast is not runtime cast, if some cannot be casted, code will not compiles. But if it compiles and cast is bad - result is undefined.

What happens when you perform a static_cast?

The static_cast operator converts a null pointer value to the null pointer value of the destination type. Any expression can be explicitly converted to type void by the static_cast operator. The destination void type can optionally include the const , volatile , or __unaligned attribute.

What is the purpose of the keyword static_cast?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

Does static_cast happen at compile time?

Although static_cast conversions are checked at compile time to prevent obvious incompatibilities, no run-time type checking is performed that would prevent a cast between incompatible data types, such as pointers.


1 Answers

Static cast takes one argument, but its argument is an expression, and expressions can include the comma operator. Comma is used in situations where you want to evaluate two or more expressions at once for their side effects, e.g.:

int i, j;
for (i=0, j=0; i < 10; i++,j++) {
    // do stuff
}

It's somewhat useful because without it you could only evaluate one expression each for the initializer, condition, and continue parts of the for loop (or any other place an expression is expected). It doesn't usually make for the clearest code, though, and the semantics are odd. As you observed, a comma-separated sequence evaluates to the value of its last expression.

like image 146
Todd Gamblin Avatar answered Sep 22 '22 15:09

Todd Gamblin