-4
#include <stdio.h>
#define sum(a, b) a+b
main()
{
printf("%d",5 * sum(2 + 1,2));
}

I met an issue in C with this test. Why the result is 18? I think 25. Thank you.

Doan Duc
  • 23
  • 6

2 Answers2

2

You are not defining a function. You are defining a preprocessor macro. That means the code a + b is being copied and pasted directly into your function.

This is what the second phase of the compiler sees.

#include <stdio.h>
#define sum(a, b) a+b
int main()
{
  printf("%d",5 * 2 + 1+2);
  return 0;
}

So the multiplication takes precedence. And you've just spotted one of the major reasons that people don't use preprocessor macros when they have a choice: they're very disorienting when it comes to operator precedence.

In general, you don't want to use preprocessor macros for things that functions can do just as well. The code you're looking for is more like this.

#include <stdio.h>

int sum(int a, int b) {
  return a + b;
}

int main() {
  printf("%d",5 * sum(2 + 1, 2));
  return 0;
}
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
1

define is the macro which is a single instruction that expands automatically into a set of instructions to perform a particular task.

so the expression 5 * sum(2 + 1,2) in printf("%d",5 * 2 + 1+2);

is expanded as 5* 2+1+2, and following the precedence rules, first the multiplication is done, so (10)+1+2, which will result to 13.

Vivek Singh
  • 114
  • 1
  • 8