I'm little bit confused. During development of one function that based on predefined parameters, pass to sprintf function exact parameters needed based on their type, I found really strange behaviour ( something like "This is %f %d example", typeFloat, typeInt ).
Please take a look at following stripped working code:
struct Param {
enum { typeInt, typeFloat } paramType;
union {
float f;
int i;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Param p;
p.paramType = Param::typeInt;
p.i = -10;
char chOut[256];
printf( "Number is %d\n", p.paramType == Param::typeInt ? p.i : p.f );
printf( "Number is %f\n", p.paramType == Param::typeInt ? p.i : p.f );
return 0;
}
My expected output would be for printf( "Number is %d\n", p.paramType == Param::typeInt ? p.i : p.f );
Number is -10
but it actually printed
Number is 0
I have put a breakpoint after initialization of the Param p, and although p.paramType
is defined as typeInt
, actual output for if
was -10.0000. Checking p.f gives some undefined value as expected, and p.i shows -10 also as expected.
But p.paramType == Param::typeInt ? p.i : p.f
in watch window evaluates to -10.000000.
I added second printf that prints it as float and now the output is
Number is 0
Number is -10.000000
So actually why this happens? Is it possible that this is a bug in Visual Studio (I use VS2012)?
Update:
std::cout<< (p.paramType == Param::typeInt ? p.i : p.f);
gives correct value of -10.