Monday, 12 June 2017

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

Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...