views:

299

answers:

1

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.

+27  A: 

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.

tgamblin
I understand the usage for it in for syntax, but I fail to grasp the functionality in a static_cast.
Statement
There is no functionality. You just do some operations using the comma operator and cast the result.
Anonymous
Ah, thanks to you and Ruben I now understand how it works, and learnt something new :)
Statement
The Syntax is: static_cast<TYPE>(EXPRESSION)Expressions happen to allow commas. Note that they're not parameters; they're operators in the expression. It doesn't really make sense to do this in a static cast, it just happens to be syntactically legal.
tgamblin
Ok. I didn't realize I could make a for loop like this : for(int i = 0; ++i, i < 10;) hehe. Not that I would go on do loops like this, but at least I feel I get the concept
Statement
That's an evil evil FOR loop. Intelligence is knowing what you CAN do. Wisdom is knowing enough NOT to do it. Congrats on possessing both!
Mr.Ree
This is an awesome answer.
James Thompson
Aside from the `for` loop example, the comma operator can be useful for logging. e.g., `static_cast<int>(log("converting to int..."), 7);`
Ben Collins