C program to swap two numbers using bitwise operator

Write a C program to input any two numbers from user and swap values of both numbers using bitwise operator. How to swap two number using bitwise operator in C programming. Logic to swap two numbers using bitwise operator in C programming.



Input first number: 22
Input second number: 65


First number after swapping: 65
Second number after swapping: 22

Required knowledge

Bitwise operators, Data types, Basic input/output

Swap two numbers without using third variable

Logic to swap two numbers using bitwise operator

There are tons of discussions going around the internet to swap two numbers without using temporary variable (third variable). We can use bitwise XOR ^ operator to swap to numbers. Bitwise XOR operator evaluates each bit of the result to 1 if corresponding bits of the operands are different otherwise evaluates 0.

Suppose two integer values a and b
Perform, x = a ^ b
Now x ^ b will evaluate to a
and x ^ a will evaluate to b.

Swapping two numbers using bitwise operator

Program to swap two numbers

 * C program to swap two numbers using bitwise operator

#include <stdio.h>

int main()
    int num1, num2;

    /* Input two numbers from user */
    printf("Enter any two numbers: ");
    scanf("%d%d", &num1, &num2);

    printf("Original value of num1 = %d\n", num1);
    printf("Original value of num2 = %d\n", num2);

    /* Swap two numbers */
    num1 ^= num2;
    num2 ^= num1;
    num1 ^= num2;

    printf("Num1 after swapping = %d\n", num1);
    printf("Num2 after swapping = %d\n", num2);

    return 0;


Enter any two numbers: 22
Original value of num1 = 22
Original value of num2 = 65
Num1 after swapping = 65
Num2 after swapping = 22

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>