Confused a little

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void twice(int n) {
   n = 2 * n;
}

int thrice(int n) {
   return n * 3;
}

int main() {
   
   int x = 1;
   twice(x); //At this point, I expect x = 2
   cout << x << endl;

   int y = 2;
   cout << thrice(y) << endl;

}


Results:

1
2
1
6


Expected Results:

1
2
2
6


Why?
Last edited on
void twice(int n) , here n value cannot be changed as it is passed by value

pass n as reference

void twice(int& n)
okay, thank you.
today is my first day of learning C++, so I didn't know the difference.
Topic archived. No new replies allowed.