ldiv(), lldiv()

Updated: April 19, 2023

Perform division on long or long long integers

Synopsis:

#include <stdlib.h>

ldiv_t ldiv( long int numer, 
             long int denom );

lldiv_t lldiv( long long numer, 
               long long denom );

Arguments:

numer
The numerator.
denom
The denominator.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The ldiv() and lldiv() functions calculate the quotient and remainder of:

numer / denom

Returns:

A structure of type ldiv_t that contains the following members:

typedef struct {
    long int quot;     /* quotient  */
    long int rem;      /* remainder */
} ldiv_t;

or a structure of type lldiv_t that contains the following members:

typedef struct {
    long long quot;     /* quotient  */
    long long rem;      /* remainder */
} lldiv_t;

Examples:

#include <stdio.h>
#include <stdlib.h>

void print_time( long ticks )
{
    ldiv_t sec_ticks;
    ldiv_t min_sec;

    sec_ticks = ldiv( ticks, 100 );
    min_sec = ldiv( sec_ticks.quot, 60 );

    printf( "It took %d minutes and %d seconds.\n",
         min_sec.quot, min_sec.rem );
}

int main( void )
{
    print_time( 86712 );
    
    return EXIT_SUCCESS;
}

produces the output:

It took 14 minutes and 27 seconds.

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes