C Programming Lecture 8 Call by Reference Scope
Call-by-Reference b For a C function to “effect” (read as “imitate”) call-by- reference: Pointers must be used in the parameter list in the function definition.Pointers must be used in the parameter list in the function definition. When the function is called, addresses of variables must be passed as arguments.When the function is called, addresses of variables must be passed as arguments.
Example of “Call-by-Reference” #include void swap(int *, int *); int main(void) { int a = 3, b = 7; printf(“%d %d\n”, a, b); /* 3 7 is printed */ swap(&a, &b); printf(“%d %d\n”, a, b); /* 7 3 is printed */ return 0; } void swap(int *p, int *q) { int tmp; tmp = *p; /* Be sure you understand this */ *p = *q; *q = tmp; }
Scope Rules b The scope of an identifier is the part of the program text in which the identifier is known or accessible. Identifiers are only accessible within the block in which they are declared.Identifiers are only accessible within the block in which they are declared. They are unknown outside the boundaries of that block.They are unknown outside the boundaries of that block.
What is a Block? A block is a compound statement that includes declarations.A block is a compound statement that includes declarations. A compound statement is a series of declarations and statements surrounded by braces.A compound statement is a series of declarations and statements surrounded by braces. –Recall that it is syntactically correct to place a compound statement wherever it is correct to place a statement.
Reusing Identifier Names b For a variety of reasons, programmers use the same identifier (such as a variable name) in different locations. b If variables are declared in different blocks (such as in different functions), then they are different variables (represent different memory locations) even if they may have the same name.
How it Works with Nested Blocks b An identifier declared in an outer block is valid in that block and all inner (nested) blocks unless an inner block redefines (declares) an identifier with the same name. If this happens, the outer block identifier is hidden, or masked, from the inner block.If this happens, the outer block identifier is hidden, or masked, from the inner block. Inner blocks may be nested to depths determined by system limitations.Inner blocks may be nested to depths determined by system limitations.
Example of Nested Blocks Using the Same Identifier Name { int a = 2; /* outer block a */ int a = 2; /* outer block a */ printf(“%d\n”, a); /* 2 is printed */ printf(“%d\n”, a); /* 2 is printed */ { int a = 7; int a = 7; printf(“%d\n”, a); /* 7 is printed */ printf(“%d\n”, a); /* 7 is printed */ } /* back to outer block */ } /* back to outer block */ printf(“%d\n”, ++a); /* 3 is printed */ printf(“%d\n”, ++a); /* 3 is printed */}