Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

//C code starts
#define mod(a)  (a>=0?a:-a)
#include<stdio.h>
int main(){
    int x,y,z;
    scanf("%d%d%d",&x,&y,&z);
    printf("%d %d %d    %d %d
",x,y,z,y-z,x-z);
    if(mod(y-x)<mod(x-z))   printf("%d %d Cat A",mod(y-z),mod(x-z));
    else if(mod(y-z)>mod(x-z))  printf("%d %d Cat B",mod(y-z),mod(x-z));
    else printf("Mouse C");
    printf("
");
}
/*code ends here*/

For the input of "1 3 2" I would expect the output to be "Mouse C" but it is not the case.

Also if we add all the variables in mod in one more bracket (e.g. if the mod(y-z) is then written as mod((y-z)) ) then the output comes as expected. So why it is going on?

question from:https://stackoverflow.com/questions/66049467/what-is-the-problem-with-this-preprocessor-in-the-code-below

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
123 views
Welcome To Ask or Share your Answers For Others

1 Answer

Macros perform direct text (or more accurately, token) substitution. So this:

mod(y-x)

Is exactly the same as this:

(y-x>=0?y-x:-y-x)

Notice that the last part is -y-x, i.e. the negation of y minus x, while what you wanted was -(y-x). This is a prime example of why macro arguments should always be placed in parenthesis as follows:

#define mod(a)  ((a)>=0?(a):-(a))

When you want to see what your macro actually does, look at your code after the preprocessor has actually done its job:

  • gcc -E file.c
  • clang -E file.c or clang --preprocess file.c
  • cl.exe /E file.c, cl.exe /P file.c, or cl.exe /EP file.c for those on windows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...