Comp 210 Lab 14: Passing Pointers

If you are using non-extended C, and are forced to manually use * and & to effect pass-by-reference, here are some notes to help you avoid bugs.
// swap
// Exchange the values of the ints *x and *y, as passed-by-reference.
//
void swap( int *x, int *y ) {
  int tmp;
  tmp = *x;
  *x = *y;
  *y = tmp;
  }

int main() {
  int myScore = 23, yourScore = 92;
  swap( &myScore, &yourScore );        // cheating on the exam?

  cout << "Hey I got " << myScore << ", you got " << yourScore << ".\n";

  swap( &100, &myScore );              // ERROR: &100 doesn't make sense!

  return 0;
  }
While it's nice to have seen the pointer perspective on things, you don't need to think that much to think of passing-by-reference. Whenever possible, avoid thinking of the pointer details; they'll only confuse you when you start thinking about pointers-to-pointers-to-int, and so on. Again, these tips are intended to allow you to forget the fact that you're messing with pointers, and are only necessary if you are using straight C. C++'s ``referent-to-int'' int& type was created for this exact same reason.
Back to Lab 14
Back to Comp 210 Home