Tuesday, May 16, 2017

How do you swap two variable?

Hi!

How do you swap two variable?

Look at this! It's a C++ code.
#include <iostream>

using namespace std;

inline void swap_var(int& _x, int& _y) {
    int _ = _x; _x = _y; _y = _;
}

inline void swap_xor(int& _x, int& _y) {
    _x ^= _y; _y ^= _x; _x ^= _y;
}

inline void swap_math(int& _x, int& _y) {
    _x += _y; _y = _x - _y; _x -= _y;
}

int main(void) {
    int a = 5;
    int b = 77201;

    cout << a << ":" << b << endl;
    swap_var(a, b);
    cout << a << ":" << b << endl;
    swap_xor(a, b);
    cout << a << ":" << b << endl;
    swap_math(a, b);
    cout << a << ":" << b << endl;
}


It's the result:
$ rm -f t; g++ -Wall -Wextra -Werror -O2 t.cpp -o t; ./t;
5:77201
77201:5
5:77201
77201:5
$


This is a C code.
#include <stdlib.h>
#include <stdio.h>

void swap_var(int* _x, int* _y) {
    int _ = *_x; *_x = *_y; *_y = _;
}

void swap_xor(int* _x, int* _y) {
    *_x ^= *_y; *_y ^= *_x; *_x ^= *_y;
}

void swap_math(int* _x, int* _y) {
    *_x += *_y; *_y = *_x - *_y; *_x -= *_y;
}

int main(void) {
    int a = 5;
    int b = 77201;

    (void) printf("%d:%d\n", a, b);
    swap_var(&a, &b);
    (void) printf("%d:%d\n", a, b);
    swap_xor(&a, &b);
    (void) printf("%d:%d\n", a, b);
    swap_math(&a, &b);
    (void) printf("%d:%d\n", a, b);

    return EXIT_SUCCESS;
}


It's the result:
$ rm -f t; gcc -Wall -Wextra -Werror -O2 t.c -o t; ./t
5:77201
77201:5
5:77201
77201:5
$

And finally, Erlang :)
-module(t).
-export([t/0]).

swap({X, Y}) ->
    {Y, X}.

t() ->
    A = {1, 2},
    swap(A).

It's the result:
$ erl
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false]

Eshell V7.3  (abort with ^G)
1> c(t).
{ok,t}
2> t:t().
{2,1}
3> q().
ok
4> $

Best regards,
Vasiliy V. Bodrov aka Bodro,
May 16, 2017.

No comments:

Post a Comment

How to reverse singly linked list in C (trivial way)

There is a beautiful morning. It's snowing. And I decided to write one more article. Today it will be just simple article where I would...