Tracing a function reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main()
{
    int a, b, c;
    void changes (int &, int &, int &);
    a=3;
    b=-5;
    c=2;
    cout<<a<<" "<<b<< " "<<c<<endl;
    changes(a,b,c);
    cout<<a<<" "<<b<< " "<<c<<endl;
    changes (c,a,b);
    cout<<a<<" "<<b<< " "<<c<<endl;
    
    
    return 0;
}

void changes (int &x, int &y, int &z)
{
    int d;
    
    d=x+y;
    z=d+1;
    x=d-2*y;
}
the first call it was simple and i got

3 -5 2
8 -5 -1

the second call to func confuse me

when i run the program i got

8 8 -9

could you help me how the the program got those answers.

thank you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

#define show(a) ( std::cout << ' ' << #a << " == " << (a) << ' ' )
#define showln(a) ( show(a) << '\n' )
#define show_assignment(lhs,rhs) { std::cout << "\tafter " << #lhs << " = " << #rhs \
                                             << " =>  " ; show(rhs) ; showln(lhs) ; }

void changes ( int& x, int& y, int& z )
{
    std::cout << "\n\tfunction changes()\n\t------------------\n" ;
    std::cout << "\ton entry =>  " ; show(x) ; show(y) ; showln(z) ;

    int d ;

    d=x+y ; show_assignment( d, x+y ) ;

    z=d+1 ; show_assignment( z, d+1 ) ;

    x=d-2*y ;  show_assignment( x, d-2*y ) ;

    std::cout << "\tat return =>  " ; show(x) ; show(y) ; showln(z) ;
}

int main()
{
    int a = 3, b = -5, c = 2 ;
    std::cout << "in main =>  " ; show(a) ; show(b) ; showln(c) ;

    changes(a,b,c);
    std::cout << "\nafter changes(a,b,c) =>  " ; show(a) ; show(b) ; showln(c) ;

    changes (c,a,b);
    std::cout << "\nafter changes(c,a,b) =>  " ; show(a) ; show(b) ; showln(c) ;
}

Output:
in main =>   a == 3  b == -5  c == 2

        function changes()
        ------------------
        on entry =>   x == 3  y == -5  z == 2
        after d = x+y =>   x+y == -2  d == -2
        after z = d+1 =>   d+1 == -1  z == -1
        after x = d-2*y =>   d-2*y == 8  x == 8
        at return =>   x == 8  y == -5  z == -1

after changes(a,b,c) =>   a == 8  b == -5  c == -1

        function changes()
        ------------------
        on entry =>   x == -1  y == 8  z == -5
        after d = x+y =>   x+y == 7  d == 7
        after z = d+1 =>   d+1 == 8  z == 8
        after x = d-2*y =>   d-2*y == -9  x == -9
        at return =>   x == -9  y == 8  z == 8

after changes(c,a,b) =>   a == 8  b == 8  c == -9
¿wouldn't be simpler to just use a step by step execution trough a debugger?
Topic archived. No new replies allowed.