Function arguments

pass-by-value and pass-by-reference
Some demo functions. Not particularly useful but for illustration purposes.
void f1 (int x) {  
       //pass-by-value arg, can not change actual arg in call
  x = x + 1;   // void function, doesn't return anything
}           // a useless function, for illustration purposes only


int f2 (int x) {
  return x * 2;     // int function, returns twice the arg
}


//reference arg (pass-by-reference) can change actual arg in call
void f3 (int &y) {    //the & makes it a reference argument
//formal arg y is a synonym for the actual arg in the call
  y = y + 1;            // void function, doesn't return anything
}                         // increments the actual arg 



// first arg is pass-by-value, second is reference arg
int f4 (int x, int &w) {
  x = x + 1;      // doesn't change actual arg in call
  w = w + x;      // actual arg changed. Adds 1st arg + 1 to 2nd arg
  return 5 * x;   // returns 1st arg +1 times 5
}
---------------------------------
Their prototypes:
void f1(int);
int f2(int);
void f3(int &);            //& must be in prototype
int f4(int,int &);
Using them:
int i, j;
i = 2;
f1(i);
// i still 2

j = f2(i);
// j now 4, i still 2

i = f2(i);
// i now 4

//most important example:
i = 2;
f3(i);    
// i now 3



i = 1;						
j = 3;
k = f4(i, j);
// k now 10, j now 5, i still 1


Remember, if the names of an actual arg and a 
formal arg are the same,it means nothing 
(they are only the same if the arg is a reference arg).
  
int x, y, z, w;
x = 2;
f1(x);
// x still 2. 
// Doesn't matter that formal arg name is x; 
//it's only given value of actual arg

x = 2;
y = 4;
z = 6;
z = f4(x,y);
// z now 15, y now 7, x still 2

w = 2;
x = 4;
z = 6;
z = f4(w,x);
// z now 15, x now 7, w still 2
Two swap functions: temp variable is needed to swap the values of two variables
int x=1, y=2, temp;
temp = x;         //swapping requires a third variable
x = y;
y = temp;  // original x


// doesn't work
void swap1 (int a, int b) {
  int temp;
  temp = a;
  a = b;
  b = temp;  // original a
}
------------

// prototype:
void swap1(int,int);

int x=2, y=3;
swap1(x,y);
// x still 2, y still 3

********************************
// swap that works  
// Arguments must be reference to change actual args in call
//Notice that code is exactly same as swap1.  
//Only difference is that args are reference.
void swap (int &a, int &b) {
  int temp;
  temp = a;
  a = b;
  b = temp;
}
-------------

// prototype
void swap(int&,int&);

int x=2, y=3;
swap(x,y);
// x now 3, y now 2

Pass-by-value actual argument can be constant, variable, expression:
f1(5);
f1(i);
f1(i*2+3);
Pass-by-reference actual argument can only be variable:
f3(i);

Exercises: write functions to:
compute quadratic formula
count chars in input
compute sum and average of input numbers

Program to compute taxable income. taxable.cpp

Program to make change change.cpp

GPA revisited for the last time. gpa again

Next (consts)


©David Wills