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?
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityBecause 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))
#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