问题
My friend sent me a exercise that he can't do:
(C++)
int main()
{
unsigned int x = 0xB0FF14a5;
unsigned int y = 0x7340c00e;
// enter code here
if(x==0x7340c00e && y==0xB0FF14a5) victory();
return 0;
}
The main goal is to run victory()
function.
Assumptions:
-max 11 chars
-You can't use: "main", "victory", "asm", "&", "*", "(", "/"
-You can use only one semicolon
I tried with #define
and some other things, but nothing (I'm not C++ master) :/
I have no idea how to solve this; thanks for helping!
回答1:
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.
回答2:
Undefined behaviour, but Works On My Computer:
x^=y^=x^=y;
UPDATE: apparently, this is well-defined since 2011; see interjay's answer.
回答3:
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
回答4:
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;
来源:https://stackoverflow.com/questions/11989319/c-swap-two-numbers-using-11-chars-of-code