1

dumb question. Just started using C++ macros, but can't understand what's wrong here.

#include <iostream>
using namespace std;

#define ABS(a) ((a < 0) ? (-a) : (a))

int main() {
    uint16_t a = 0xf0, b = 0xf8;
    cout << a << " " << b << " " << a - b <<" " << ABS(a - b) << endl;
    int c = a, d = b;
    cout << c << " " << d << " " << c - d << " " << ABS(c - d) << endl;
}

The output is following:

240 248 -8 -488
240 248 -8 -488

Tried with signed and unsigned, but the macro result is always the same.

Svalkash
  • 11
  • 1

1 Answers1

5

Let's take this macro:

#define ABS(a) ((a < 0) ? (-a) : (a))

And let's expand just this usage of this macro:

ABS(a - b)

If you go ahead and substitute verbatim (because that's how macros work) a-b everywhere a occurs in the macro, this is what you get:

((a-b < 0) ? (-a-b) : (a-b))

You can pretty much use your text editor's search/replace function to do this. The mistake is now glaringly obvious.

Your macro should be:

#define ABS(a) (((a) < 0) ? -(a) : (a))

(I threw in an extra set of parenthesis, just to avoid further trouble down the road).

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148