Is it bad to use the increment operator ++
on floats? It compiles but I find it counter-intuitive. In what cases is using ++
on float variable justified and better than += 1.0f
? If there are no use cases, is there a respectable C++ style guide that explicitly says that ++
on float is evil?
For float ++
does not increment by the smallest possible value, but by 1.0. 1.0f has no special meaning (unlike integer 1). It may confuse the reader causing him to think that the variable is int. For float it is not guaranteed that operator++ changes the argument. For example the following loop is not infinite:
float i, j;
for (i=0.0, j=1.0; i!=j;i=j++);
Consequently doing ++
immediately after --
does not guarantee that the value is unchanged.
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
.