This post demonstrates how to swap numbers in a single statement without using a temporary variable.
For your reference, representing all the forms of how to swap numbers without using a temporary variable.
The above code throws the following warning if you are using any IDEs like codeblocks etc. Ignore the warning, the code just works fine.
Please share your thoughts on this post in the comments section.
For your reference, representing all the forms of how to swap numbers without using a temporary variable.
Using addition and subtraction operators -
int main() { int a,b; a = 10; b = 9; a = b-a; b = b-a; a = a+b; return 0; }
Using XOR operator -
int main() { int a,b; a = 10; b = 9; a = a^b; b = a^b; a = a^b; return 0; }
In a single line -
int main() { int a,b; a = 10; b = 9; a = (a+b) - (b=a); return 0; }
The above code throws the following warning if you are using any IDEs like codeblocks etc. Ignore the warning, the code just works fine.
warning: operation on 'b' may be undefined
[-Wsequence-point]
Please share your thoughts on this post in the comments section.
Good one :)
ReplyDeleteThank you.
Delete*Whistle* Well then
ReplyDeleteThank you.
Delete