The below given code is written to satisfy the condition (x == x+2) to be returning true in C.
#include<stdio.h>
#define x 2|0
int main()
{
printf("%d",x==x+2);
return 0;
}
In the above code why the printf()
is printing 2
( if I write x+3
I get 3
and so on ).
Can someone explain how the given macro is working.
What is the use of |
operator in C and what does the macro
#define x 2|0
mean? I read about macros in other questions but no question explained similar kind of example.
TL;DR; Read about operator precedence.
+
binds higher than ==
which binds higher than |
.
After preprocessing, your printf()
statement looks like
printf("%d",2|0==2|0+2);
which is the same as
printf("%d",2|(0==2)|(0+2));
which is
printf("%d",2|0|2);
Word of advice: Do not write this type of code in real scenario. With minimal level of compiler warning enabled, your code produces
source_file.c: In function ‘main’: source_file.c:4:12: warning: suggest parentheses around comparison in operand of ‘|’ [-Wparentheses] #define x 2|0 ^ source_file.c:8:21: note: in expansion of macro ‘x’ printf("%d\n\n",x==x+2); ^ source_file.c:4:12: warning: suggest parentheses around arithmetic in operand of ‘|’ [-Wparentheses] #define x 2|0 ^ source_file.c:8:24: note: in expansion of macro ‘x’ printf("%d\n\n",x==x+2);
So, the moment you change the MACRO definition to something sane, like
#define x (2|0)
the result will also change, as the explicit precedence then will be guaranteed by the parenthesis.