xref: /reactos/sdk/lib/ucrt/stdlib/imaxdiv.cpp (revision 04e0dc4a)
1*04e0dc4aSTimo Kreuzer //
2*04e0dc4aSTimo Kreuzer // imaxdiv.cpp
3*04e0dc4aSTimo Kreuzer //
4*04e0dc4aSTimo Kreuzer //      Copyright (c) Microsoft Corporation. All rights reserved.
5*04e0dc4aSTimo Kreuzer //
6*04e0dc4aSTimo Kreuzer // Defines imaxdiv(), which performs a signed divide using intmax_t operands
7*04e0dc4aSTimo Kreuzer // and returns the quotient and remainder.  No validation of the arguments is
8*04e0dc4aSTimo Kreuzer // done.
9*04e0dc4aSTimo Kreuzer //
10*04e0dc4aSTimo Kreuzer #include <inttypes.h>
11*04e0dc4aSTimo Kreuzer 
12*04e0dc4aSTimo Kreuzer 
13*04e0dc4aSTimo Kreuzer 
imaxdiv(intmax_t const numerator,intmax_t const denominator)14*04e0dc4aSTimo Kreuzer extern "C" imaxdiv_t __cdecl imaxdiv(intmax_t const numerator, intmax_t const denominator)
15*04e0dc4aSTimo Kreuzer {
16*04e0dc4aSTimo Kreuzer     imaxdiv_t result;
17*04e0dc4aSTimo Kreuzer 
18*04e0dc4aSTimo Kreuzer     result.quot = numerator / denominator;
19*04e0dc4aSTimo Kreuzer     result.rem = numerator - denominator * result.quot;
20*04e0dc4aSTimo Kreuzer 
21*04e0dc4aSTimo Kreuzer     // Fix incorrect truncation:
22*04e0dc4aSTimo Kreuzer     #pragma warning(push)
23*04e0dc4aSTimo Kreuzer     #pragma warning(disable: 4127)
24*04e0dc4aSTimo Kreuzer     static bool const fix_required = (-1 / 2) < 0;
25*04e0dc4aSTimo Kreuzer     if (fix_required && result.quot < 0 && result.rem != 0)
26*04e0dc4aSTimo Kreuzer     {
27*04e0dc4aSTimo Kreuzer         result.quot += 1;
28*04e0dc4aSTimo Kreuzer         result.rem -= denominator;
29*04e0dc4aSTimo Kreuzer     }
30*04e0dc4aSTimo Kreuzer     #pragma warning(pop)
31*04e0dc4aSTimo Kreuzer 
32*04e0dc4aSTimo Kreuzer     return result;
33*04e0dc4aSTimo Kreuzer }
34*04e0dc4aSTimo Kreuzer 
35*04e0dc4aSTimo Kreuzer 
36*04e0dc4aSTimo Kreuzer 
37*04e0dc4aSTimo Kreuzer /*
38*04e0dc4aSTimo Kreuzer  * Copyright (c) 1992-2010 by P.J. Plauger.  ALL RIGHTS RESERVED.
39*04e0dc4aSTimo Kreuzer  * Consult your license regarding permissions and restrictions.
40*04e0dc4aSTimo Kreuzer V5.30:0009 */
41