Q:

I got stuck on following c programming, did not concept of 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);
}

After executing above code, i am getting unexpected output, i am not getting the exact logic behind this.so guys please help me out.
Output of above code: 
10 0 0

A:

The macro swap is not a C function, instead the preprocessor inserts the macro as is in the place of the macro invocation, so the code looks like this:
if( i > j)
temp=i; i=j; j=temp;;

And after reformatting the code is
if( i > j)
    temp=i;
i=j;
j=temp;
;

Only the assignment to temp is done if the condition is true, the other two assignments are always done unconditionally.
This can be solved in two ways: Put the macro invocation inside a statement block:
if( i > j)
{
    swap( i, j );
}

Or make the macro body a block:
#define swap(a,b) do { temp=(a); (a)=(b); (b)=temp; } while (0)

The convention to put multi-statement macros inside a do { ... } while (0) statement is because otherwise you get an empty statement (like you do now, see above), which can cause problems when expanding the macro as part of e.g. an if else statement.

