What is the purpose of the div() library function?

后端 未结 5 2156
一个人的身影
一个人的身影 2020-11-28 16:46

When C has the / operator to divide two numbers, what is the purpose of having the div() library function?

Is there any scenario where /

5条回答
  •  爱一瞬间的悲伤
    2020-11-28 17:18

    As other people have mentioned, div() will give you both the quotient and the remainder. This is because the (software) integer division algorithm that most C runtimes use computes both at the same time.

    If the target computer does not have a hardware divider, the / operator typically gets turned into a call to div() and the remainder gets thrown away. The same thing happens with the % operator except that it's the quotient that gets tossed. So if you're doing something like this:

    quot = a / b;
    rem = a % b;
    

    you're calling the divide routine twice (and divide is pretty slow if your computer doesn't do it in hardware). So it's faster to use div() to get both.

    (Of course, it's also less readable and whether you actually gain any performance advantage depends on your specific platform and compiler. You should only ever switch to div() if you've determined that it's a performance bottleneck. Remember what Knuth said about premature optimization.)

提交回复
热议问题