Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...