functions

Will someone explain each step of hand tracing this program. I don't understand how the program gets the output of 9.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

void myFunction(int x) {
 x = -1;
}
int main() {
 int x = 9;
 myFunction(x);
 cout << x;
 return 0;
}
//The output is 9
Hello phatski

line 10 defines "x" and sets it to 9.

Line 11 calls the function "myFunction" which sets a copy of "x" to "-1". at line 8 the function ends and looses scope, so the copy of "x" that was set to "-1" is lost

Line 12 prints "x" which is still "9" because nothing has been changed.

Hope that helps,

Andy
Thank you, Andy, I thought that x= -1 on line 7 would carry over in myFunction on line 11 and since it comes after line 10 where x=9, I thought the output would be -1. If line 7 had "return x= -1 " then the output would be -1, correct?
If you pass 'x' by reference its value will be -1 after the function call.
Last edited on
Thank you, everyone, my question has been answered.
Topic archived. No new replies allowed.