Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer Division in C++11

Tags:

c++

c++11

I was noticing some wording changes to section 5.6 for C++11. (I'm looking at the draft C++ standard N3242, dated 2011-02-28.) The new (draft) standard includes the sentence:

"For integral operands the / operator yields the algebraic quotient with any fractional part discarded;"

This statement is not in 5.6 of the 03 standard (ISO-IEC-14882-2003), but I don't think this is a change, is it? This is how C and C++ has worked for years unless I've lost my mind (which may have happened anyway).

like image 257
John Avatar asked Dec 23 '11 14:12

John


People also ask

Is there integer division in C?

(Integer Division) In the C Programming Language, the div function divides numerator by denominator. Based on that division calculation, the div function returns a structure containing two members - quotient and remainder.

How do you find division in C++?

The division operator / computes the quotient (either between float or integer variables). The modulus operator % computes the remainder when one integer is divided by another (modulus operator cannot be used for floating-type variables).


2 Answers

You're not going mad.

A footnote to 5.6/4 said:

[C++03 footnote 74]: According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

In C++11 this behaviour is explicitly required rather than being "preferred"; the change is listed in the compatibility section:

[C++11: C.2.2]:
Change: Specify rounding for results of integer / and %
Rationale: Increase portability, C99 compatibility.
Effect on original feature: Valid C++ 2003 code that uses integer division rounds the result toward 0 or toward negative infinity, whereas this International Standard always rounds the result toward 0.

like image 96
Lightness Races in Orbit Avatar answered Oct 20 '22 18:10

Lightness Races in Orbit


Almost. In C++03 the sign of the remainder for % (in which terms both were specified) was unspecified, as such rounding could go away from zero in certain situations too. Compare with the C++03 footnote:

According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

In practice however, this almost never made any difference.

like image 26
PlasmaHH Avatar answered Oct 20 '22 18:10

PlasmaHH