YarrakVar
YarrakVar

Reputation: 5

C++ Pointers Trace

I make a trace and I get 20 as a result from a = a + deg1(&a); operation. But the result is 40. Could you guys explain it?

#include <iostream>

using namespace std;

int deg1(int*p){
    *p = 20;
    int i = *p;
    return i;
}

int deg2(int x){
    return x * 2;
}

int main()
{
    int a = 10;
    a = a + deg1(&a);
    cout << a << '\n';
    int b = 20;
    b = b +deg2(b);
    cout <<b;
    return 0;
}

Upvotes: 0

Views: 451

Answers (2)

Yonghun  Jung
Yonghun Jung

Reputation: 1

I'm not good at English

a = a + deg1(&a);

code execution order is like this

001524C9 lea eax,[a]

001524CC push eax

001524CD call deg1 (01513A2h) <- call deg1

001524D2 add esp,4

001524D5 add eax,dword ptr [a] <- operator +

001524D8 mov dword ptr [a],eax

a = a + deg1(&a)

first call deg1

then deg1 return 20 and make a = 20

therefore a = a + deg1(&a);

a = 20 + 20;

a = 40

Upvotes: 0

HolyBlackCat
HolyBlackCat

Reputation: 96286

The behavior is undefined. GCC indeed prints 40, but Clang prints 30.

In a + deg1(&a), the read of a in the lhs is unsequenced relative to the write to a in the function body.

Upvotes: 8

Related Questions