Sunday, December 21, 2008

Week 2, Day 2

Haven't been in a programming mood as of late... but I pushed myself to do this one anyway after taking a few days off.

Today's "Class"
References. A reference are just a pseudonym of a variable you already have declared. They cannot be null... EVER. Or rather, they SHOULD not ever be null or referencing a variable that does not exist. References are fantastic, enabling you to use many of the useful features of pointers, WITHOUT the extra syntax and the extra difficulty of doing so. Here is a simple definition of a reference:
...
int myVariable = 5;
int & rMyVariable = myVariable;
...


Now, whether you use the variable name "myVariable" or "rMyVariable", the same piece of data is utilized. That might not seem like a very useful thing to do, and in that little snippet... it wouldn't be. The power behind references is the ability to pass the entire variable into a function and let the function actually edit the variable. Here is a sample program that does just this:
// Example of how to use references in a function
#include <iostream>

using namespace std;

void swapValues( int & x, int & y );

int main()
{
    int x = 15, y = 33;
    cout << "x: " <<
    swapValues( x, y );
    cout << "x: " <<>
    return 0;
}

void swapValues( int & rX, int & rY )
{
    int temp;
   
    cout << "swapping...\n";
    temp = rX;
    rX = rY;
    rY = temp;
}


If you do compile that guy and run it, you should see exactly what you THINK you should see. The restrictions for references are as follows: (1) you MUST initialize the reference (since you cannot have a reference that is null) and (2) you CANNOT reassign a reference. References should be used in place of pointers when at al possible. You can obviously reference ANY type of variable or any object, just like with pointers.
References also have the added bonus of reducing memory usage and speeds up the program slightly. This doesn't matter too very much when you are just passing in some number, but using user defined objects with references is a very good idea.

Summary and Workshop
Summary was quick and to the point. Reviewed the essentials of references. The exercises were rather tedious to me. I actually skipped a few since I just wasn't in the mood and I knew the topic pretty well from the chapter. I may finish up the exercises another day, not sure yet. Either way, the exercises were very easy and didn't really make me think any.

No comments: