C++ swap two numbers using 11 chars of code [closed]

ε祈祈猫儿з 提交于 2019-12-08 13:06:29

Use the XOR swap algorithm:

x^=y^=x^=y;

This is equivalent (usually, see below) to:

          //x==A,   y==B
x ^= y;   //x==A^B, y==B
y ^= x;   //x==A^B, y==A
x ^= y;   //x==B,   y==A

It works because XORing by the same number twice gives you the original number.

In C++03 the single-expression version is undefined behavior so may not work correctly on all compilers/platforms. This is because there is no sequence point between modification and use of variables.

In C++11, it is well-defined. The standard says (5.17.1):

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

Undefined behaviour, but Works On My Computer:

x^=y^=x^=y;

UPDATE: apparently, this is well-defined since 2011; see interjay's answer.

13 characters and violates other rules, but gets the job done and too cute not to post:

#include<iostream>

void victory()
{
   std::cout << "Yes we can\n";
}

int main()
{
    unsigned int x = 0xB0FF14a5;
    unsigned int y = 0x7340c00e;
    #define if(x)
    if(x==0x7340c00e && y==0xB0FF14a5) victory();
    return 0;
}

Output on Ideone

Look at this algorithm: XOR swap algorithm But you will get a compile warning like:

warning: operation on ‘x’ may be undefined

if you use this algorithm in just one line

x ^= y ^= x ^= y;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!