Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c - What is the problem with this preprocessor in the code below?

//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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...