0

I am trying to convert a char digit to an integer: {'1' -> 1, '2' -> 2, ..., '9' -> 9} and then multiply that integer by another integer. This is my attempt so far.

#define toDigit(c) c - '0'

printf("%d\n", toDigit('3') * 5);

Expected output: 15

Actual output: -189

Why is this not working?

Tom Finet
  • 487
  • 1
  • 7
  • 21

1 Answers1

1

When your macro is expanded, the code looks like this:

printf("%d\n", '3' - '0' * 5);

at which point, the usual arithmetic precedence kicks in, and the multiplication happens first. So you get 51-(48*5), which gives the answer you see.

You could avoid this be putting your macro expansion in parantheses like this:

#define toDigit(c) ((c) - '0')

Ideally, avoid macros for this purpose. Or for any other purpose, for that matter. They are error prone, and can easily be replaced by a function, like this:

int toDigit(char c) { return c - '0'; }

You can use this inside complicated expressions without any issue.

cigien
  • 57,834
  • 11
  • 73
  • 112