iOS Development

Course No. 10-152-139

Chapter 10 — Pass By Reference

Writing pass-by-reference functions

  • In C, and most languages, a function can only return one value.
  • What if you actually want a function to return more than one value? That might be handy!
  • We get around this limitation with the concept of pass-by-reference.
  • We pass the address of a variable to a function instead of the variable. How do we do that? With the &.
  • Here’s a very simple function.
  • When we call it we have to send the address of a variable to it, not the variable!
  • Notice that this function doesn’t return a value. Can it change count? Yup!
  • How does this work?


  • When we call passMeTheAddress(&count); we are passing the 1192 to the function, not 5.
  • C knows that it’s a pointer because of the function declaration.
    • void passMeTheAddress(int *number) {
  • So, C goes to the address in ram that is 1192 and assigns the value.
  • How does it know how many bytes to use?
    • Because it’s a pointer to an int. C knows how big an int is.
  • Where this technique is really useful is when you want more that one return value.

Avoid dereferencing NULL

  • It’s a really bad thing to access the address of NULL. It’s zero!
  • We can avoid this by checking the address before we use it.