question regarding div / std::div implementation

Paul Eggert eggert@cs.ucla.edu
Wed Apr 20 21:38:00 GMT 2016


On 04/20/2016 02:15 PM, Daniel Gutson wrote:
> OK with no inline asm, but a libcall might be expensive specially in a
> tight loop and messes with predictions;
> a builtin is nonportable as well.

In practice, C programs that need integer quotient and remainder 
typically don't call 'div'. They just use % and /, and compilers are now 
smart enough to do just one machine-level operation to get both quotient 
and remainder. For example, time/offtime.c has this macro:

#define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))

which should work just fine as-is. In theory one could change this to 
use div/ldiv/lldiv, but why bother making the code way more complicated?

As the 'div' function family was designed back when C compilers were not 
that smart and is largely obsolete now, simplicity would appear to be 
more important than performance here. Perhaps someone someday will work 
up the energy to get 'div' removed from the C standard.



More information about the Libc-alpha mailing list