I am having trouble understanding how to obtain the correct values outputted by the following C++ code when trying to solve it by hand.
#include <iostream>
using namespace std;
int f(int a, int & b,int *c){
a += 1;
b += 3;
*c += 4;
return a+b+(*c);
}
int main() {
int a = 3, b = 4,c = 5;
cout << "total: " << f(b,c,&a) << endl;
cout << "a= " << a << " b= " << b << " c= " << c << endl;
a = 3, b = 4,c = 5;
cout << "total: " << f(a,a,&a) << endl;
cout << "a= " << a << " b= " << b << " c= " << c << endl;
return 0;
}
I know the result should be:
total: 20
a= 7 b= 4 c= 8
total: 24
a= 10 b= 4 c= 5
But everytime I try to solve this code by hand (attempt to write out the steps and assignments on a piece of paper) I can't seem obtain the correct total or values. Can anyone help me understand what is happening inside the function with a, b, and c (maybe a step-by-step explanation?). There must be something I am not understanding with the referencing/dereferencing or the pointers that is causing mistakes in my logic. Even ChatGPT is spitting out the incorrect answer after trying to execute the code...
For example if I try the first set of of inputs inside the function, here's what I understand:
- int a = 4;
- int &b = 5; //since c = 5
- int *c = &a; //&a = 3
Then I start to execute the body of the function:
- a += 1 now gives me a = 5;
- b += 3 now gives me c = 8 since b is a reference to c so it really only is c that changes;
- *c += 4 now takes the value stored in &a initialized as 3 and adds 4 so a's new value is 7;
The final tally is a = 7, b = 4 (hasn't changed), and c = 8. These values are correct, but the return portion of the function does not work with these values:
a+b+(*c) should be 7+4+(7), but the result of that is 18, while the correct answer is 20.
What's worst is that if I use the same logic for the second time the function is called, my values are incorrect but my total is correct... I'm lost.