C ++ swaps two numbers using 11 characters of code

My friend sent me an exercise that he cannot 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 the victory() function.
Assumptions:
max 11 characters
You cannot use: "main", "victory", "asm", "&", "*", "(", "/"
-You can use only one semicolon

I tried with #define and some other things, but nothing (I'm not a C ++ master): /
I do not know how to solve this; thanks for the help!

+1
source share
4 answers

Use the XOR exchange algorithm :

 x^=y^=x^=y; 

This is equivalent (usually see below):

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

This works because XORing to the same number twice gives you the original number.

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

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

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

+12
source

Undefined but works on my computer:

 x^=y^=x^=y; 

UPDATE : it appears to have been clearly defined since 2011; see interjay answer.

+8
source

13 characters and violates other rules, but performs the task and is too cute not to post messages:

 #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; } 

Conclusion on Ideone

+4
source

Look at this algorithm: XOR exchange algorithm But you will get a compilation warning:

 warning: operation on 'x' may be undefined 

if you use this algorithm in only one line

 x ^= y ^= x ^= y; 
+1
source

Source: https://habr.com/ru/post/984353/


All Articles