Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer vs floating division -> Who is responsible for providing the result?

I've been programming for a while in C++, but suddenly had a doubt and wanted to clarify with the Stackoverflow community.

When an integer is divided by another integer, we all know the result is an integer and like wise, a float divided by float is also a float.

But who is responsible for providing this result? Is it the compiler or DIV instruction?

like image 899
nsivakr Avatar asked Aug 15 '10 16:08

nsivakr


2 Answers

That depends on whether or not your architecture has a DIV instruction. If your architecture has both integer and floating-point divide instructions, the compiler will emit the right instruction for the case specified by the code. The language standard specifies the rules for type promotion and whether integer or floating-point division should be used in each possible situation.

If you have only an integer divide instruction, or only a floating-point divide instruction, the compiler will inline some code or generate a call to a math support library to handle the division. Divide instructions are notoriously slow, so most compilers will try to optimize them out if at all possible (eg, replace with shift instructions, or precalculate the result for a division of compile-time constants).

like image 150
Carl Norum Avatar answered Sep 23 '22 18:09

Carl Norum


The compiler will decide at compile time what form of division is required based on the types of the variables being used - at the end of the day a DIV (or FDIV) instruction of one form or another will get involved.

like image 20
Will A Avatar answered Sep 21 '22 18:09

Will A