Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I happen to know of other methods used to swap two variables without a temporary variable like addition and subtraction, bitwise and so on. But I want to know why this method does not give correct result. The code is meant for C language.

int a=15, b=7;
a= b+(1 && (b=a)*0);
printf("%d %d",a, b);
return 0;

What I have tried:

Since && is a sequence point the first b should return 7 and second one should be assigned to 15?

So the output should be a=7 and b=15. But it is not.
Posted
Updated 18-May-21 19:13pm

Quote:
So the output should be a=7 and b=15. But it is not.

Obviously, your compiler use different rules than yours. And compiler rules may evolve with optimizations.
My robust swap methods are:
C++
int a=15, b=7;
int tmp= a; a= b; b=tmp; // and I let compiler optimizations remove the variable.

or
C++
int a=15, b=7;
a^=b; b^=a; a^= b; // swap by xor
 
Share this answer
 
Comments
Vishwash 2021 19-May-21 3:36am    
So what does C standard tell about the given code? This appeared in a test where they want us to tell whether this will work or not.
Patrice T 19-May-21 5:26am    
The only way to know for good is to look at assembly generated by compiler.
C++
a= b+(1 && (b=a)*0);
shouldn't that use the logical comparison, == for (b=a) ?

Also, why are you multiplying by 0? The effect is (1 && 0).
 
Share this answer
 
Comments
Patrice T 19-May-21 0:59am    
"shouldn't that use the logical comparison, == for (b=a) ?"
No he wants initial value of a being assigned to new b.
"Also, why are you multiplying by 0? The effect is (1 && 0)."
it is a complicated way to isolate the assignment to b.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900