Domanda

So I have the following program:

# define swap(a,b) temp=a; a=b; b=temp; 

int main() {
int i, j, temp;
i = 5;
j = 10;
temp = 0;
if (i > j)
    swap(i, j);
printf("%d %d %d", i, j, temp);
}

This results in:

10, 0, 0

What I don't understand is why the if (5 > 10) condition was executed as "true" even though 5 is not bigger than 10.

È stato utile?

Soluzione

This should teach you to avoid macros if at all possible and always, always use braces in control flow statements.

After macro expansion, your code will read:

if (i > j)
    temp = i;
i = j;
j = temp;

See the problem?

Altri suggerimenti

This is because at the time of compilation swap(i, j); is being replaced by temp=a; a=b; b=temp;. Now the expanded macro looks like

 if(i > j)
    temp = i;
    i = j;
    j = temp;  

At the time of execution only temp = i will not execute for i > j to be false.
If you wanna treat swap(i, j) like a function, then change your macro definition to

#define swap(a,b) do {temp=a; a=b; b=temp;} while (0) 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top