Is using increment (operator++) on floats bad style?

后端 未结 4 428
孤街浪徒
孤街浪徒 2020-12-08 10:45

Is it considered \"bad style\" to use the increment operator (++) on floats? It compiles just fine but I find it smelly and counter-intuitive.

The question: In what

相关标签:
4条回答
  • 2020-12-08 11:03

    In general ++/-- is not defined for floats, since it's not clear with which value the float should be incremented. So, you may have luck on one system where ++ leads to f += 1.0f but there may be situations where this is not valid. Therefore, for floats, you'll have to provide a specific value.

    ++/-- is defined as "increment/decrement by 1". Therefore this is applicable to floating point values. However, personally i think, that this can be confusing to someone who isn't aware of this definition (or only applies it to integers), so i would recommend using f += 1.0f.

    0 讨论(0)
  • 2020-12-08 11:03

    When you add a lots of 1.0 to a float, because of floating point arithmetic you might be a little off in the end

    The best way is to do

    for ( int i = 0; i < 100; i++ )
    {
         float f = 2.433f + i * 1.0f;
    

    instead of

    for ( float f = 2.433f; f < 102.433f; f += 1.0f )
    

    In the second case the floating point arithmetic error adds up and in the first case it doesn't. As certain users have pointed out in comments below adding integrals floats might not accumulate errors but in general it is a good idea to avoid it.

    0 讨论(0)
  • 2020-12-08 11:14

    There is nothing wrong with using ++ and -- on float or double operands. It simply adds or subtracts 1. That's what it's for!

    0 讨论(0)
  • 2020-12-08 11:15

    It's bad style. ++ and -- are intended to set an lvalue to its next or previous value, like the next or previous integer, the next or previous element in an array (for pointers), the next or previous element in a container (iterators), etc.

    Next and previous values are not well-defined for floats. Do f += 1. explicitly.

    0 讨论(0)
提交回复
热议问题