why is z not simply 30 here?

Why is z not simply 30 here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// more than one returning value
#include <iostream>
using namespace std;

void prevnext (int x, int& prev, int next)
{
  prev = x-1;
  next = x+1;
}

int main ()
{
  int x=30, y, z;
  prevnext (x, y, z);
  cout << "Previous=" << y << ", Next=" << z;
  return 0;
}
By value vs. by reference. Lets inline the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main ()
{
  int x = 30;
  int y; // undefined
  int z; // undefined

  // prevnext (x, y, z);
  int f_x = x;
  int & f_y = y;
  int f_z = z; // undefined
  f_y = f_x - 1; // y becomes 29 via reference;
  f_z = f_x + 1; // f_z becomes 31, z remains undefined

  cout << "Previous=" << y << ", Next=" << z;
  return 0;
}
because you pass z as a copy (while y is passed as a reference). Hence next is modified but z is not changed (while y is)
I understand that z is not CHANGED, but z is ment to be 30 then, so why it does not write out z=30?
I don't understand the question. If z is not changed, then why would you expect it to output 30?

Or perhaps more to the point, if that's what you want to happen, the code must be modified to make it so. The most straightforward way would be to pass z by reference. That is change function prevnext() to pass next in the same way as prev.

see tutorial page for more information:
http://www.cplusplus.com/doc/tutorial/functions2/
Last edited on
but z is ment to be 30 then,


It's not. You never set it to 30 (or anything). z is left uninitialized, so it could be anything.


This code:

int x=30, y, z;

initializes x, but not y or z. So x is 30... but y and z contain garbage.
Topic archived. No new replies allowed.