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
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
.
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.
There is nothing wrong with using ++
and --
on float or double operands. It simply adds or subtracts 1. That's what it's for!
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.