0
#include <stdio.h>

int f1(int *x, int y) {
    y++;
    (*x)++;
    return *x + y;
}

int main() {
    int x = 10, y = 5;
    int z = f1(&x, y);
    printf("x=%d y=%d z=%d\n", x, y, z);
}

I get the answer as x=11 y=5 z=17. Can someone explain this?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 4
    Did you run this in a debugger and stepped through? What did you see? – Sourav Ghosh Sep 30 '22 at 07:55
  • 1
    Your function takes a *copy* of `y` (it's passed by value) and doesn't make any changes to the original variable. – Adrian Mole Sep 30 '22 at 07:56
  • The `y` in `main()` and the `y` in `f1()` are different variables. BTW: the `x` in `f1()` is a **pointer** to the `x` in `main()` (they are also different variables). – pmg Sep 30 '22 at 07:59
  • The best way to see what a program is doing is to run it line by line in a [debugger](https://stackoverflow.com/q/25385173/12149471), while monitoring the values of all variables. – Andreas Wenzel Sep 30 '22 at 08:25

2 Answers2

1

Check the comments.

#include <stdio.h>

int f1(int *x,int y)
{
    y++;  // incrementing y, which was 5, to 6.
    (*x)++;  // incrementing the value-at-address-x, which was 10, to 11
    return *x+y;  // add value-at-address-x, 11, and value of y, 6 == 17, return that.
}

int main(void)          //correct signature of main in hosted environment
{
    int x=10,y=5;
    int z=f1(&x,y);
       //any changes made to the value stored at address x will reflect here, 
       // any changes made to the value of y will be local to the function call.

    printf("x=%d y=%d z=%d\n",x,y,z);
       // updated x, unchanged y, and returned z.

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

The formal arguments x and y in f1 are different objects in memory from the variables x and y in main.

When you call z=f1(&x, y);, the expressions &x and y are fully evaluated and the results of those expressions are copied to the formal parameters x and y (this is what we mean when we say C passes function arguments by value).

So the formal parameter x stores the address of the variable x and the formal parameter y stores the value 5.

Since the formal parameter y is a different object in memory from the variable y, changing its value has no effect on the y in main.

The expression *x is f1 acts as kinda-sorta an alias for the variable x, so changing the value of *x in f1 does change the value of x in main.

John Bode
  • 119,563
  • 19
  • 122
  • 198