2

Here's come Arduino code.

#define M(x, y) x * y;
void setup() {
  Serial.begin(9600);
  Serial.println(M(3 + 2, 4 + 2));
}
void loop() {
}

Why is the result 13?

1 Answer 1

16

Because M(3 + 2, 4 + 2) gets replaced to 3 + 2 * 4 + 2 and then the normal priority of operations does the multiply before the addition.

This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.

If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.

#define M(x, y) ((x) * (y))
2
  • 3
    Always also surround the whole macro in parenthesis; otherwise you can have the same problem in the other direction: If you do #define A(x, y) (x) + (y), then A(1, 2) * 3 will expand to (1) + (2) * 3 = 7, instead of ((1) + (2)) * 3 = 9, like one would expect. Mar 11, 2018 at 2:42
  • 5
    And trailing semicolon here will also make problems.
    – Ruslan
    Mar 11, 2018 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.