[ create a new paste ] login | about

Link: http://codepad.org/zvoqQcYh    [ raw code | output | fork ]

GHF - C++, pasted on Aug 15:
#include <iostream>
#include <cstdlib>

int32_t nabs(int32_t i);

int main() {
    const int a = 51;
    const int b = 85;

    if (nabs(a - b) > -100) {
        std::cout << "a and b are within 100 of each other." << std::endl;
    }

    return EXIT_SUCCESS;
}

/**
 * Negative absolute value. Used to avoid undefined behavior for most negative
 * integer (see C99 standard 7.20.6.1.2 and footnote 265 for the description of
 * abs/labs/llabs behavior).
 *
 * @param i 32-bit signed integer
 * @return negative absolute value of i; defined for all values of i
 */
int32_t nabs(int32_t i) {
#if (((int32_t)-1) >> 1) == ((int32_t)-1)
    // signed right shift sign-extends (arithmetic)
    const int32_t negSign = ~(i >> 31); // splat sign bit into all 32 and complement
    // if i is positive (negSign is -1), xor will invert i and sub will add 1
    // otherwise i is unchanged
    return (i ^ negSign) - negSign;
#else
    return i < 0 ? i : -i;
#endif
}


Output:
1
a and b are within 100 of each other.


Create a new paste based on this one


Comments: