Go through the following C code
# define swap(a,b) temp=a; a=b; b=temp;
main( )
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j)
swap ( i, j );
printf ( "%d %d %d", i, j, temp);
}
Compiler Output:
10 0 0
I am Expecting this output
10 5 0
Why am I wrong??
It's the lack of braces. This is one of the common pitfalls with macros. Let's see what happens:
if(i > j)
swap(i, j);
becomes:
if(i > j)
temp = a; a = b; b = temp;;
Made a little more readable:
if(i > j)
temp = a;
a = b;
b = temp;
So the lines a = b; and b = temp; will always be executed, they fall outside the if body.
Either put braces around the if, or the macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With