iOS Development

Course No. 10-152-139

Chapter 5 — Functions

When should I use a function?

  • Code that is run multiple times.
  • Code that is complicated. Breaking the code up into parts increases readability and makes coding easier.

How do I write and use a function?

  • Function structure


How functions work together

  • Let’s see it work in the debugger.


Local variables, frames, and the stack

  • Frames are like little chalkboards that functions can write on. Each function gets it own frame.
  • As a function is called, its frame is created and put on top of the stack of frames.

Scope

  • Any pair of braces defines its own scope restricting the availability of variables declared within them.
  • Line 7 shows a variable that only has scope within the if statement.

The return statement

  • If a function starts with anything other than void then it must have a return statement.

Global and static variables

  • Fully global variables
  • Line 4 shows a variable that is truly global, even if we have other files in our app.
  • This is not a good idea!
  • A static variable. This is the better way.
  • A static variable is only available in the file where it is declared.
    • Ah, much better and easier to organize.