13

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.

4

1 に答える 1

30

静的キャストは 1 つの引数を取りますが、その引数は式であり、式にはカンマ operatorを含めることができます。コンマは、2 つ以上の式の副作用を一度に評価したい状況で使用されます。たとえば、次のようになります。

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

これがないと、 for ループの初期化子、条件、および継続部分 (または式が期待されるその他の場所) に対してそれぞれ 1 つの式しか評価できないため、多少便利です。ただし、通常は最も明確なコードにはなりません。セマンティクスは奇妙です。ご覧のとおり、コンマ区切りのシーケンスは最後の式の値に評価されます。

于 2009-02-27T09:54:28.510 に答える