Can I compare and add a floating-point number to an integer in C?

前端 未结 9 1277
余生分开走
余生分开走 2020-12-14 02:50

Can I compare a floating-point number to an integer?

Will the float compare to integers in code?

float f;     // f has a saved predetermined floating         


        
9条回答
  •  借酒劲吻你
    2020-12-14 03:20

    Mixed-mode arithmetic (arithmetic between operands of different types and/or sizes) is legal but fragile. The C standard defines rules for type promotion in order to convert the operands to a common representation. Automatic type promotion allows the compiler to do something sensible for mixed-mode operations, but "sensible" does not necessarily mean "correct."

    To really know whether or not the behavior is correct you must first understand the rules for promotion and then understand the representation of the data types. In very general terms:

    • shorter types are converted to longer types (float to double, short to int, etc.)
    • integer types are converted to floating-point types
    • signed/unsigned conversions favor avoiding data loss (whether signed is converted to unsigned or vice-versa depends on the size of the respective types)

    Whether code like x > y (where x and y have different types) is right or wrong depends on the values that x and y can take. In my experience it's common practice to prohibit (via the coding standard) implicit type conversions. The programmer must consider the context and explicitly perform any type conversions necessary.

提交回复
热议问题