LearnFrenzy
Sign in Take a free test

Bitwise Operators · Predict the Output · Question 5

XOR swap without a temporary – output Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

int main(void) {
    int a = 7, b = 12;
    a ^= b;
    b ^= a;
    a ^= b;
    printf("%d %d\n", a, b);
    return 0;
}
  • A 12 7 Correct
  • B 7 12
  • C 11 11
  • D 0 0
Correct Answer: Option A

After the first line a holds a ^ b. Then b ^= a gives b ^ (a ^ b) = a, and a ^= b gives (a ^ b) ^ a = b. The values are swapped. (It breaks if both names refer to the same variable.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular