What is the operation flow in this code? C/C++

Viewed 131

I'm studying for my final exam and I have the following code example:

#include <iostream>

using namespace std;

int* f(int *i) {
    (*i)--;
    return i;
}

void main() {

    int a;
    int b = 2019;

    a = (*f(&b))--;

    printf("%d\n", a);
    printf("%d\n", b);
}

When I print the values, a = 2018 and b = 2017. Why is that? Why a get 2018 and after that b gets --?

2 Answers

A pointer to b is passed in f() under the parameter int *i. f dereferences this pointer to b and decrements b by one using this code

(*i)--

So b starts as 2019, it goes through f where it is decremented to 2018.

f() also returns a pointer to an int, which in this case points to the address of b. So when this call happens

a = (*f(&b))--;

f(&b) returns a pointer to b after decrementing it

a = (*(&b))--;

The expression *(&b) is evaluated to deference &b i.e. get the value of b which is 2018 at this point, this is assigned to a which is why a is 2018.

Now, what does x-- mean? It means x = x-1, so this translates to

(*(&b)) = (*(&b))-1

so b goes to 2017 in this case.

@mrMan Well brother if you look closely at the statement a = (*f(&b))--; there is a post decrement happening here. This (*f(&b)) is a pointer function which means this holds a reference and not a value so as soon as return statement in function executed a is assigned a value of 2018 as it got decremented in the function above but now (*f(&b)) this right here holds a reference to value 2018 which got changed but has address of b so when (*f(&b))-- this happens it actually decreases the value of b further more. Hope your question got cleared. Happy coding!!!!!!!!!! :)

Related