-1
#include<stdio.h>
#define mul(p,q) p*q
int main(){
int a=5;
printf("%d",mul(a+3,a-2));
return 0;
}

I expected this to print 24, but I got 18. Why is that happening?

  • You can run the pre-processor `cpp` and see its output to understand how it works. – Mohamed Moanis Oct 16 '16 at 16:01
  • It would be better to write "I expected this to print 24, but I got 18. Why is that happening?" The way you wrote it, it sounds like you think the compiler is malfunctioning. Arguably this *is* a design error in the language, but it can't ever be fixed, and when debugging you should always *start* with the assumption that you have made a mistake, not that you have found a bug in a library or the compiler. – zwol Oct 16 '16 at 16:04

2 Answers2

3

It's basically, find and replace before compiling. Your code becomes

int main(){
    int a=5;
    printf("%d",a+3*a-2);
    return 0;
}

instead of #define mul(p,q) p*q you should do #define mul(p,q) ((p)*(q)). Then your code would become as below and you would get the expected answer.

int main(){
    int a=5;
    printf("%d",((a+3)*(a-2)));
    return 0;
}
Drew Chapin
  • 7,779
  • 5
  • 58
  • 84
1

Whenever the preprocessor does something surprising to your code, you can find out what it was by inspecting the preprocessed output. With a Unixy compiler, use the -E command-line option:

$ gcc -E test.c | sed -ne '/main/,$p'
int main(){
int a=5;
printf("%d",a+3*a-2);
return 0;
}

(The sed bit is to eliminate thousands of lines of irrelevant material produced by the inclusion of stdio.h.)

Macro expansion has produced

printf("%d",a+3*a-2);

Do you understand why you get a surprising answer now?

This is a very common problem people have with the C preprocessor. The GNU CPP manual has an entire section entitled "Operator Precedence Problems" discussing it. The short version is that your macro definition should have been

#define mul(p,q) ((p)*(q))
zwol
  • 135,547
  • 38
  • 252
  • 361