29
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

一時変数を使わずスワップする方法

Posted at

排他的論理和を使って、一時変数を使わずに、2つの変数の値を交換することができます。

swap.c
#include <stdio.h>
 
int main(void) {
        int x=10,y=20;
        printf("x:%d y:%d\n",x,y);
        x ^= y;
        y ^= x;
        x ^= y;
        printf("x:%d y:%d\n",x,y);
        return 0;
}
output
x:10 y:20
x:20 y:10

他の言語でも同様にできるはずです。

29
27
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?