C++ cstdlib div, ldiv , lldiv functions

The C++ <cstdlib> div, ldiv and lldiv returns the structure div_t, ldiv_t and lldiv_t.The declaration of the function is given below.

div_t div(int numer , int denom);
ldiv_t ldiv(long int numer , long int denom);
lldiv_t lldiv(long long int numer , long long int denom);

numer -The numerator value.

denom -The denominator value.

Return type
div_t , ldiv_t and lldiv_t -These structures contain two data members which hold the remainder and quotient of ‘numer/denom'( numer divided by denom ).

Link :C++ cstdlib div_t , ldiv_t and lldiv_t structures

Some points to note:

i) The structures div_t , ldiv_t and lldiv_t contain two data members ‘rem’ and ‘quot’ and their type is same as the type of ‘numer’ and ‘denom’.The ‘rem’ hold the remainder of ‘numer/denom’ and the data member ‘quot’ hold the quotient of ‘numer/denom’.The names are fixed for all the structures and in all compiler.

ii) If you use ‘div’ function assign the return value to the object of ‘div_t’ structure type,if ‘ldiv’ is used assign the return value to the object of ‘ldiv_t’ structure type and if ‘lldiv’ is used assign the return value to ‘lldiv_t’ structure type.This is necessary to avoid any discrepancy in the type of the data members and the arguments type.

iii) If the result cannot be computed i.e. ‘numer’ or ‘denom’ is over large or either of them is not valid ,the ‘rem’ and ‘quot’ is also not defined.

Code example

div_t d ;

d=div( 67 , 5 );

cout<< “d.rem=” << d.rem << endl ///remainder of ’67/5′
<< “d.quot=” << d.quot << endl ; ///quotient of ’67/5′

lldiv_t lld;
lld=lldiv( 90 , 50 ) ;

cout<< “lld.rem=” << lld.rem << endl ///remainder of ’90/50′
<< “lld.quot=” << lld.quot ; ///quotient of ’90/50′


d.rem= 2

More information about div , ldiv and lldiv functions

If ‘denom’ is greater than ‘numer’

Now if denominator value is greater than numerator value i.e. denom>numer ,the quotient is 0 and the remainder is equal to numerator value(numer).Since the arguments are integer type -also the data member of div_t or ldiv_t or lldiv_t structure- and as we know integer type does not support a decimal point value system so,there is no way to represent any quotient smaller than 0.Code example

ldiv_t ld;

ld=ldiv( 4 , 5 );

cout<< d.rem << endl
<< d.quot << endl ;



If ‘denom’ is 0

In this case the program break.This is expected since any number divide by 0 is infinity but integer type does not support ‘infinity’ or ‘NaN’ value hence the compiler would not know how to handle such evaluation.Note floating point type support ‘infinity’ and ‘NaN’ value,if the arguments and the data members type were floating point type the operation could have been handled appropriately.We might say integer types are incompetent in such case.