|
A variable that is defined inside some scope is a local variable:
#include <stdio.h> int main( int argc, char* argv[] ) { // Start of a scope int x; // Local variable int y = 4; // Local variable x = y + 3; printf( "%d %d\n", x, y ); } |
|
DEMO: /home/cs255001/demo/C/set1/scoping-err1.c (gcc -c scoping-err1.c)
|
I will "unpack" this statement with some examples
Consider the following program with 2 variables with name x:
#include <stdio.h> int main( int argc, char* argv[] ) { int x = 4; // Scope of x starts here { int x = 7; // x is overshadowed by x here } } |
(1) variable x=4 is in the outer scope and (2) variable x=7 is in the inner scope
DEMO: demo/C/set1/scoping-demo.c
Example of scoping:
#include <stdio.h> int main( int argc, char* argv[] ) { int x = 4; // Scope of x starts here printf("%d\n", x); // prints 4 { int x = 7; // x is overshadowed by x here } } |
The variable x in printf("%d\n", x); refers to int x = 4;
Example of scoping:
#include <stdio.h> int main( int argc, char* argv[] ) { int x = 4; // Scope of x starts here { printf("%d\n", x); // prints 4 int x = 7; // x is overshadowed by x here } } |
The variable x in printf("%d\n", x); refers to int x = 4;
Example of scoping:
#include <stdio.h> int main( int argc, char* argv[] ) { int x = 4; // Scope of x starts here { int x = 7; // x is overshadowed by x here printf("%d\n", x); // prints 7 !!! } } |
The variable x in printf("%d\n", x); refers to int x = 7;
Example of scoping:
#include <stdio.h> int main( int argc, char* argv[] ) { int x = 4; // Scope of x starts here { int x = 7; // x is overshadowed by x here } // End of overshadowing ! printf("%d\n", x); // prints 4 } |
The variable x in printf("%d\n", x); refers to int x = 4;
Example of scoping error:
#include <stdio.h> int main( int argc, char* argv[] ) { printf("%d\n", x); // Error: x undefined int x = 4; // Scope of x starts here { int x = 7; // x is overshadowed by x here } } |
The variable x was used before the start of the scope of the variable x !
Example of scoping error:
#include <stdio.h> int main( int argc, char* argv[] ) { int x; { int y = 4; } printf( "%d\n", y ); // Error } |
The variable y was used after the end of the scope of the variable y !
|
DEMO: demo/C/set1/scoping1.c + scoping1.java
Where can you use (= access) a local variable in C:
|
Purpose of local variables:
|
Parameter variables are defined in the function header:
void funcName( int param1, float param2 )
{
int localVar1;
float localVar2;
...
}
|
What is the scope of parameter variables ?
The scope of parameter variables is same as local variables that are defined at the start of the function:
void funcName( |
Note: parameter variables are "real" variables and they are created when the arguments are passed (= copied)