Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to swap two variables in one line in C?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.13k
    Comment on it

    How to swap two variables in one line in C?

    C program to swap two variables in single line

    #include <stdio.h>
    void main()
    {
        int a = 5;
        int b = 10;
        (a ^= b), (b ^= a), (a ^= b); 
        printf("Swapped values of a and b are %d %d",a, b);
    }
    

    Output:

    Swapped values of x and y are 10 5

    Explanation:
    Comma operator has least precedence and associativity is from left to right.In this C program in third line the expression is separated by comma,so evaluation is from left to right.By using comma operator the expression can be of one line and XOR is used to swap values of a and b.

    a = a XOR b which is 15
    b = b XOR a which is 5
    a = a XOR b which is 10

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: