Search code examples
cfunctionpointersfunction-parameter

Change Value of Variable in Function in C


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?
}

Solution

  • 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.