39

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 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 possble 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.

6
  • 2
    There's a big difference between j++ and ++j
    – luke
    Dec 19, 2011 at 12:32
  • Why don't you split your question-answer pair into a proper question and a proper answer? You might get more votes if people agree with you.
    – vitaut
    Dec 19, 2011 at 12:36
  • 3
    +1 - I agree that ++ has a connotation of "advance to the next value", not "increase by the magic number 1". And in that sense it does not make much sense to use with floats. Still, I doubt there will be a satisfying answer to this question.
    – tenfour
    Dec 19, 2011 at 12:37
  • The question is whether there is a case where ++ on float is justified. If no is there a C++ style guide that explicitly says that ++ on float is evil?
    – Muxecoid
    Dec 19, 2011 at 12:45
  • 3
    How shocking! C++ compiles something that doesn't make all that much of a sense ;) ? Dec 19, 2011 at 13:04

5 Answers 5

26

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.

3
  • 6
    It is defined for all arithmetic types and pointer: 'The value of the operand object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true'
    – fefe
    Dec 19, 2011 at 12:44
  • Also gcc does not complain about float++ when compiling with -Wall.
    – Muxecoid
    Dec 19, 2011 at 12:55
  • This didn't work for an opencl kernel with a++ where a is a 32-bit float and device is 1080ti. I think this is a simple driver bug. Nov 30, 2017 at 21:47
20

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.

11
  • 7
    Yes. (But why multiply by 1.0f? float f = 2.433f + i; is enough.)
    – TonyK
    Dec 19, 2011 at 12:45
  • 5
    While it is true that certain fractional values have no exact representation as floats, integral values always do and the result of adding two floats with integral values (which seems to be what the OP is doing) will never have a round-off error.
    – Ferruccio
    Dec 19, 2011 at 13:14
  • 10
    Actually, adding 1.0f consecutively to 0.0f is exact as long as it is less than 2²⁴ for IEEE single.
    – kennytm
    Dec 19, 2011 at 13:14
  • 5
    @Ferruccio: Not correct. In single precision, only integers up to 2^24, in double precision, up to 2^53 can be stored exactly (because of the size of the significand). Dec 19, 2011 at 14:16
  • 4
    @phresnel: What I was saying was that round-off error is not an issue when adding floats with integral values. The range of integral values in a float is smaller than an int. And you can overflow a float by adding 1.0 many times just like you can overflow an int by adding 1 many times, but the answer had to do with round-off error which is not going to happen by adding two floats with integral values. If I somehow implied that you could store the same range of integers in a float that you can store in an int, that was not my intention.
    – Ferruccio
    Dec 19, 2011 at 17:53
13

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

3
  • That's actually untrue as far as I'm concerned, according to 'standard' that doesn't really specify the behavior here, i wouldn't rely on that. Dec 19, 2011 at 13:07
  • 5
    @ScarletAmaranth The standard does specify the behavior, very precisely. (That doesn't necessarily mean that it's a good idea.) Dec 19, 2011 at 13:35
  • 1
    @TonyK My apologies fine sir, disregard my previous comment, i though it's behavior is undefined when dealing with floats (considering a lot of floating-point-interpretation problems.) So yes, it simply increments by one :) Dec 19, 2011 at 13:42
9

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.

6
  • 3
    I'm not sure I follow what you're saying. As far as the increment and decrement operators are "intended" to do anything, they're intended to increment and decrement any type they're defined for - including floating point types. The only difference between f += 1. and ++f is that the former promotes f to a double for the calculation. Dec 19, 2011 at 13:01
  • 2
    @Mike: I think that larsmans and the questioner are in effect asserting that it was a mistake (of bad style) in the C standard to define ++ for floating point types. They assert this based on their perception of the intended purpose of that operator for other types, and that just because the definition can be applied to any type with a += assignment operator that takes 1 on the rhs, doesn't mean the purpose applies. Dec 19, 2011 at 13:34
  • @SteveJessop: Exactly. I had an arguement on the subject with my collegue so now I'm looking for a style guide that supports my point. :)
    – Muxecoid
    Dec 19, 2011 at 14:06
  • 1
    Exactly, I choose to disagree with the Standard's authors on this one; ++ shouldn't have been defined on floating-point types. It just doesn't make sense given the meaning of ++ on all other types and it's confusing.
    – Fred Foo
    Dec 19, 2011 at 16:58
  • 2
    @ColeJohnson: by "float" (ordinary font), I mean either float, double or long double.
    – Fred Foo
    May 6, 2013 at 8:54
1

I realise this is an old question, but I'd like to point out something that none of the other answers have brought up (though some comments have aluded to it).


For those who can't be bothered to read the full explanation of why the behaviour of ++ and -- may be confusing for some people, I'll cut straight to the main point:

Whether or not a behaviour is well understood by the people working on the code is more important than whether the behaviour is well defined.

In the words of Donald Knuth:

The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly.

(Emphasis mine.)

If everyone on your team understands the behaviour then there is a reasonable case to use the operators.

If some of your team struggle with the ++ and -- operators when used in conjunction with floating points and claim that they find += 1 and -= 1 to be more readable then there is a good case to avoid ++ and -- in favour of improving readability for your other team members.

Whilst this is a decision that ought to be made on a per-team basis, personally I would argue that += 1 and -= 1 in the case of floating point types is certainly never less clear than ++ and --, whilst the fact we have answers disagreeing about the clarity of ++ and -- is evidence enough that the meaning is not 'obvious' to everyone.

If there were another compelling reason to prefer ++ and -- (e.g. in the case of iterators only random access iterators support += and -=, hence ++ and -- are more idiomatic) then it would be worth greater debate or consideration, but given that ++ and -- are equivalent to += 1 and -= 1 for floating points, readability should be the sole consideration.


Why the behaviour may be confusing is a bit of an intricate topic...

While ++ and -- do generally mean += 1 and -= 1 in the context of most arithmetic types, when used with other types that definition doesn't entirely hold and frankly seems a bit of a naive definition.

In the case of iterators ++ and -- mean 'advance iterator' and 'retreat iterator'. One could argue that's a similar behaviour to adding and subtracting 1, but in this situation the '1' is not a concrete entity which can lead to confusion.

Thus for the case of iterators a more appropriate analogy is the idea that ++ means 'next value' and -- means 'previous value' (other languages have a similar idea in the form of succ and pred functions).

For the case of iterators the analogy of 'successor' and 'predecesor' functions holds much better, which is precisely where the confusion comes from - some people take ++ and -- to mean 'successor' and 'predecessor' and in the context of floating point values that would imply adding the 'epsilon' value.

In the case of pointers, whilst technically ++ does means += 1 and -- does mean -= 1, the 1 in this case doesn't actually mean the numerical value of 1, numerically it actually means 1 * sizeof(*pointer) (i.e. advance the pointer by the size of the object it is pointing to).

In the case of non-pointer iterators, there may well be no use of +=. Consider a linked list, where the behaviour of the iterator would be something along the lines of this->pointer = this->pointer->next.

Once again, the idea of the 'successor' and 'predecessor' functions is a better fit than the idea of 'adding one'.

This is where the problem arises with the floating point types (float, double, long double). For those who understand ++ and -- to be the 'successor' and 'predecessor' functions (or 'advance' and 'retreat' if you prefer), the behaviour is not obvious because by that analogy += std::numeric_limits<T>::epsilon and -= std::numeric_limits<T>::epsilon would also be valid implementations.

Another way of looking at this is that 1 is the smallest possible value by which an integer can increase, but 1 is not the smallest possible value by which a floating point value can be increased.

Thus to anyone who understands these alternative analogies the behaviour of ++ and -- on floating point types may be non-obvious, which is precisely why they should be avoided.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.