Search code examples
ctypesmacrosc-preprocessor

Defining macro and using data types to find an absolute value


I'm trying to solve this problem from my textbook in the Preprocessor section.

The problem asks to define a macro ABSOLUTE(num) to calculate an absolute value of some number or arithmetic expression.

I resolved it by including <stdlib> and defining a function with abs(num):

#include <stdio.h>
#include <stdlib.h>
#define ABSOLUTE(num) printf("The absolute value of %i is %i\n", (num), abs(num))

int main()
{
    ABSOLUTE(-1);
    ABSOLUTE(3-4);
    ABSOLUTE(7);
    ABSOLUTE(-8-3);

    return 0;
}

But before I was trying to manipulate data types, because the book section was reviewing them and said nothing about the library. However, it didn't work quite obviously.

#include <stdio.h>
#define ABSOLUTE(num) printf("The absolute value of %i is %u\n", (num), (num))

int main()
{
    ABSOLUTE(-1);
    ABSOLUTE(3-4);
    ABSOLUTE(7);
    ABSOLUTE(-8-3);

    return 0;
}

I understand the mistake here, but wonder if that's even possible to solve this problem by manipulating data types or other preprocessor directives.


Solution

  • To compute the absolute value, simply negate the value if it is negative:

    #define ABSOLUTE(x) ((x) < 0 ? -(x) : (x))

    This will work with any type for which the unary - operator is defined (subject to overflow), which is nicer than using abs since abs requires int.