C++ community. i have Tasks and need yor help!!!.

please, help me to find, what is the final result and how it works.
it's code
#include <iostream>
using namespace std ;
void swapnum(int ∗i , int ∗ j ) {
∗ i = ∗ i + ∗ j ;
∗ j = ∗ i − ∗ j ;
∗ i = ∗ i − ∗ j ;
}
int main(void) {
int a = 10;
int b = 20;
swapnum(&a , &b ) ;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <algorithm>
using namespace std ;

void swapnum(int *i, int *j ) {
    *i = *i + *j;
    *j = *i - *j;
    *i = *i - *j;
}
int main(void) {
    int a = 10;
    int b = 20;
    // If you like silly 1970's inspired assembler hacks
    swapnum(&a, &b) ;
    cout << "a=" << a << ", b=" << b << endl;
    // And if you're living in the 21st Century...
    std::swap(a,b);
    cout << "a=" << a << ", b=" << b << endl;
    return 0;
}

The first problem is you're assuming (erroneously) that signed integer math is always modulo-n rounded (it isn't).

The second is that it's a silly trick from the 1970's (much like https://en.wikipedia.org/wiki/XOR_swap_algorithm ).

Judging from all the funny symbols, it looks like you copied it directly from some web page / word document / pdf. Instead of actually trying it yourself and finding out.



Last edited on
To be fair, compilers are aware of pointless programming puzzles (I don't think it was ever smart to do this even in the 1970s), and can sometimes optimize stupid swaps to the same code as normal swaps: https://gcc.godbolt.org/z/SXJO_O (the OP's example fails to optimize, something about parameter passing seems to break it.. likely alias analysis)
Last edited on
A long time ago (286 era here) I tried a BUNCH of ways to swap (int, double, etc type data) more efficiently. (The best answer at that time was to use assembly language and push/pop the built in stack). Trying to avoid the temporary and extra copy, you know. I tried xor trick (a^=b, b^=a, a^=b) and the addition subtraction one and pointers and all kinds of stuff. Ironically, in C++, nothing ever beat the temporary, esp if the temp was static (of course, it would be, for speed).

This used to be a popular interview question.
Topic archived. No new replies allowed.