Rushikesh Posted on Dec 17, 2018 Swap two integers in 'C' programming Without using third variable #cprogram #c #clanguage #swap C programming (2 Part Series) 1 Swap two integers in 'C' programming 2 Swap two integers in 'C' programming Without using third variable C program to swap two integers without using third variable Top comments (4) Subscribe Personal Trusted User Create template Templates let you quickly answer FAQs or store snippets for re-use. Submit Preview Dismiss Collapse Expand Frank Puffer Frank Puffer Frank Puffer Follow Software developer, among other things Location Europe Joined Oct 28, 2018 • Dec 17 '18 • Edited on Dec 17 • Edited Dropdown menu Copy link Hide While it does have some educational value to show that this is possible, this method has two issues: Both a = a + b and a = a - b can cause an overflow. I can't imagine many situations where saving a few bytes really makes up for the loss in readability. Collapse Expand Günther Jena Günther Jena Günther Jena Follow Joined Aug 15, 2018 • Dec 30 '18 • Edited on Dec 30 • Edited Dropdown menu Copy link Hide It also works with XOR (avoiding the overflow problem): a = a ^ b b = a ^ b a = a ^ b Enter fullscreen mode Exit fullscreen mode Collapse Expand Jason C. McDonald Jason C. McDonald Jason C. McDonald Follow Author. Speaker. Time Lord. (Views are my own) Email codemouse92@outlook.com Location Time Vortex Pronouns he/him Work Author of "Dead Simple Python" (No Starch Press) Joined Jan 31, 2017 • Feb 8 '19 Dropdown menu Copy link Hide Agreed, this is definitely the way to do it. Collapse Expand Joe Carnuccio Joe Carnuccio Joe Carnuccio Follow automotive embedded Location So Cal Education BE(EE), BSc(Comp Sci, Physics) Work Senior Development Engineer, Embedded Software at Karma Automotive Joined Jan 13, 2019 • Feb 6 '19 • Edited on Feb 6 • Edited Dropdown menu Copy link Hide reduced to one line: a ^= b ^= a ^= b; Code of Conduct • Report abuse Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse
Top comments (4)
While it does have some educational value to show that this is possible, this method has two issues:
Both
a = a + b
anda = a - b
can cause an overflow.I can't imagine many situations where saving a few bytes really makes up for the loss in readability.
It also works with XOR (avoiding the overflow problem):
Agreed, this is definitely the way to do it.
reduced to one line:
a ^= b ^= a ^= b;