-1

The final values for x and y should be x = 4 and y = 21. I understand why y = 21, but why is x = 4? Should "a = 5" not change the value to 5? Thanks

int f(int a, int *b){
    a = 5;
    *b = *b + 3*a;
}

int main(){
    int x, y;
    x = 4;
    y = 6;
    f(x, &y);
    // What are x and y now?
}
Enea Dume
  • 3,014
  • 3
  • 21
  • 36
Joe
  • 17
  • 1
  • 3
  • 4
    C uses pass by value for all function arguments. Changing a variable within a function does not change the value of the original variable that was passed in. – kaylum May 14 '17 at 06:13
  • @kaylum Would you mind elaborating on that? – Joe May 14 '17 at 06:14
  • Best if you consult your text book. This fundamental of C language is covered in any basic C book or tutorial. – kaylum May 14 '17 at 06:14
  • Passing by Value means that the function gets a copy of the arguments, so any changes made inside the function are not reflected in the original variables. – GAURANG VYAS May 14 '17 at 06:15

1 Answers1

2

In your function a is passed by value not by reference, so the x value will no tb e changed. While b is passed by reference, so value of y is changed.

LF00
  • 27,015
  • 29
  • 156
  • 295