Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap function in Function-Like Macros

Tags:

c

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

like image 209
Megamind Avatar asked Aug 13 '26 17:08

Megamind


1 Answers

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.

like image 54
Kninnug Avatar answered Aug 16 '26 11:08

Kninnug