Passing parameters BY REFERENCE

  1. A parameter is passed by reference if:

  2. Because Java ALWAYS passes parameters by value, we have to resort to C++ to illustrate this fundamental concept

    You need to know the pass-by-reference concept for the tests
    (This is is NOT about Java, but about programming - Java is just the tool for teaching programming)

    Example:
          #include <iostream.h>
    
          void myMethod(int& a)  // Specifies that a is passed by reference
          {
             a = a + 1;
          }
    
          int main(int argc, char **argv)    
          {
    	 int i = 10;
    
    	 myMethod(i);                  // Invoke "myMethod" and pass i
    	 cout << "i = " << i << endl;  // Prints i
          }
    
    

    Pictorially:

    A very concrete example:

    In pass-by-reference:
    • The computer knows that the address of the variable was passed in.

    • The computer will FIRST use the address to locate the actual variable and THEN use this variable in all operations that involve the corresponding formal parameter

  3. Therefore:

    This program from a moment ago:
          #include <iostream.h>
    
          void myMethod(int& a)  // Specifies that a is passed by reference
          {
             a = a + 1;
          }
    
          int main(int argc, char **argv)    
          {
    	 int i = 10;
    
    	 myMethod(i);                  // Invoke "myMethod" and pass i
    	 cout << "i = " << i << endl;  // Prints i
          }
    
    

    Will print: i = 11.

    Here is a DEMO program: click here

  4. FYI: here is how you specify "pass-by-value" in C++