c - Why does this program output 8? -


this question has answer here:

#include <stdio.h> #define abs(x) x > 0 ? x : -x  int main(void) {   printf("%d\n", abs(abs(3 - 5)));   return 0; } 

why program above output 8 , not 2 while program below outputs 2?

#include <stdio.h>  int abs(int x) {   return x > 0 ? x : -x; }  int main(void) {   printf("%d\n", abs(abs(3 - 5)));   return 0; } 

short answer "because macro not function".

long answer macro parameters expanded text of program, c compiler sees long expression:

3 - 5 > 0 ? 3 - 5 : -3 - 5 > 0 ? 3 - 5 > 0 ? 3 - 5 : -3 - 5 : -3 - 5 > 0 ? 3 - 5 : -3 - 5 

in expansion, negative sign applies 3, not (3-5), yielding negative 8.

although can work around issue placing parentheses around x in macro definition, defining inline function better choice.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -