Local Variables And Function Parameters
Last time when we looked at
static
variables declared inside functions, we touched on local
variables. Today we'll focus on local variables and function
parameters.
Local variables in C and Objective-C are declared like this:
// local variable examples
void myFunction() {
// declare some local variables ...
int i; // uninitialized, will have some random value
NSString *s = @"foobar";
double sqrtOf2 = sqrt(2);
// do stuff ...
}
Local variables are not initialized to zero,
NULL
or nil
by default the way global
variables are. It's important to initialize a local variable before
you use it, otherwise its initial value will be something random and
almost certainly not something useful. Function parameters are very
similar to local variables, except that their value is defined by the
caller of the function.
// function parameter examples
void yourFunction(int i, NSString *s, double d) {
// do stuff ...
}
In very old C code, you may sometimes see function parameters declared
like this:
// old function parameter style
myOldFunction(i, s, d) // only parameter names go here
int i;
NSString *s;
double d;
// parameter types are defined between
// the parameter list and curly brace
{
// do stuff ...
}
This old style is called K&R C (for Kernighan & Ritchie, the
authors of
The
C Programming Language book) and has been replaced by the
modern ANSI C style you're used to, but you many occasionally see it in
very old code or examples. (In fact, the function return type is
optional in K&R C and defaults to int
if not given.)
Function parameters are available for the complete time that the
function is executing. Local variables however can have a more limited
lifespan. Typically, local variables are local to a function body, but
they can also be local to the body of an if
,
for
, while
and do-while
statement:
void printSquares() {
int x;
for (x = 0; x < 10; ++x) {
int x_squared = x * x; // only valid in the for loop
printf("%i^2 = %i\n", x, x_squared);
}
// x_squared no longer valid
// x still valid
}
In fact, you can even use a set of curly braces alone to create a new
local variable scope:
void someFunction() {
int x;
// new local scope
{
int foo = 10; // local variable foo now valid
// ... do something with foo
}
// foo no longer valid
// x still valid
}
In older versions of C and Objective-C, all local variables had to be
declared at the start of a function or statement block. So something
like this:
void someFunction() {
int x = 10;
printf("x = %d\n", x);
int y = 20; // not allowed before C99
printf("y = %d\n", y);
}
would not compile. The C99
standard changed this to allow local variables to be declared at
any point in a function, something that C++ has always allowed. By
default, Xcode Objective-C projects compile using C99 rules (this is
set by the C Language Dialect build setting in Xcode or the
-std=c99
command line parameter to gcc
).
Next time, we will look at
instance
variables of Objective-C classes.