# Quick dividing by a float question

This topic is 4580 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

(In c++) When dividing by a float, is it worth checking if the float is equal to 0, if it was would it throw an exception or something?

##### Share on other sites
No, dividing by 0.0 yields plus or minus infinity which floats are able to represent.

##### Share on other sites
Is it worth it? Yes.
Do you need to? No.

General recomendation is to not use exceptions for normal control flow. So if you expect your value to be 0 frequently, or if your value can be valid with value of 0, then check it.

Exceptions would be more suitable in cases where the divisor should, or even "could" not be 0.

##### Share on other sites
It also depends on what you're going to do with the result.

I've had code that shoved essentially random numbers into some complicated set of floating point operations. There were any number of places where there was potential to divide by zero. I didn't check anything until I got the final result out and then checked that instead.

On the other hand if getting a bad result out is more problematic in your app then that sort of fast & loose philosophy can make it harder to debug why you're getting division by zero in the first place.

Floating-point division by zero will not automatically throw an exception of any sort on architectures I'm familiar with. I don't know if the standard says anything about this sort of thing - at least for C/C++, if you're programming in Ada or something stricter the story would probably be different.

*Integer* division by zero is a completely different beast.

##### Share on other sites
Quote:
 Original post by Anon MikeFloating-point division by zero will not automatically throw an exception of any sort on architectures I'm familiar with. I don't know if the standard says anything about this sort of thing - at least for C/C++, if you're programming in Ada or something stricter the story would probably be different.

In C++ the results are undefined for both integer and floating point arithmetic. I've had pretty good luck with assuming floating pont division by zero goes to +/- infinity, but technically I can't assume that unless my compiler documentation says I can.

CM

##### Share on other sites
You can enable floating point exception is MSVC look here http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/floapoint.asp

1. 1
Rutin
33
2. 2
3. 3
4. 4
5. 5

• 13
• 76
• 11
• 10
• 14
• ### Forum Statistics

• Total Topics
632968
• Total Posts
3009584
• ### Who's Online (See full list)

There are no registered users currently online

×