c++ - Union float and int -
i'm little bit confused. during development of 1 function based on predefined parameters, pass sprintf function exact parameters needed based on type, found strange behaviour ( "this %f %d example", typefloat, typeint ).
please take @ 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 %d\n", p.paramtype == param::typeint ? p.i : p.f ); printf( "number %f\n", p.paramtype == param::typeint ? p.i : p.f ); return 0; }
my expected output printf( "number %d\n", p.paramtype == param::typeint ? p.i : p.f );
number -10
but printed
number 0
i have put breakpoint after initialization of param p, , although p.paramtype
defined typeint
, actual output if
-10.0000. checking p.f gives undefined value expected, , p.i shows -10 expected. p.paramtype == param::typeint ? p.i : p.f
in watch window evaluates -10.000000.
i added second printf prints float , output is
number 0 number -10.000000
so why happens? possible bug in visual studio (i use vs2012)?
update:
std::cout<< (p.paramtype == param::typeint ? p.i : p.f);
gives correct value of -10.
this because resulting type of expression p.paramtype == param::typeint ? p.i : p.f
float (only value different depending on paramtype
), first format string expects integer.
the following should work expect:
printf("number %d\n", (int)(p.paramtype == param::typeint ? p.i : p.f));
the cout
version gives expected output because type of expression being inserted (float
) deduced automatically, , formats float. same second printf
.
Comments
Post a Comment