Variable Scope 1
Scope The places in your code that can read and/or write a variable. Scope starts at the location where you declare the variable There may be holes in the scope! Scope ends at the end of the block in which the declare occurs Usually, the function in which the variable was declared 2
Simple Example Block in which j is declared #include <stdio.h> int main(int argc, char **argv) { int j; for(j=0; j<argc; j++) { printf( Argument %d = %s\n,j,argv[j]); } return 0; } Scope of j 3
Block doesn t have to be a function! You can define a variable inside a sub-block of a function 4
Internal Example Block in which k is declared #include <stdio.h> int main(int argc, char **argv) { int j; for(j=0; j<argc; j++) { int k=j+1; printf( Argument %d = %s\n,k,argv[j]); } return 0; } Scope of k 5
Global Variable Declared outside of a block Scope is from declaration to the end of the C file! 6
Global Example Block in which nc is declared #include <stdio.h> int nc=0; int myfunc(int n) { nc++; return n; } int main(int argc, char **argv) { int j; for(j=0; j<argc; j++) myfunc(2); printf( myfunc called %d times\n,nc); return 0; } Scope of nc 7
Global Variable Pros & Cons Advantages Simple and intuitive Enables functions to communicate data with each other Remembers between function calls as well as within function calls Disadvantages Increases the outside information a function needs to be aware of (binding) Prevents re-use of functions Remembers between function calls as well as within function calls 8
Holes in Scopes If the a variable is declared inside a sub-block with the same name as a variable that already exists outside the sub-block, the internal declaration temporarily replaces the external definition! Causes multiple versions of a variable with the same name! Compiler only allows you to work with one of the versions at any given time. You have to know which version of the variable the compiler will use! 9
Example Scope Hole { int i; int j=7; Scope of outside j for (i=0; i<3; i++) { } int j=i+1; printf( j=%d\n,j); } printf( j=%d\n,j); Scope of inside j (Hole for outside j) j=1 j=2 j=3 j=7 10
Variable Class Automatic Created/Initialized on entry to block Destroyed on exit from block Static Created/Initialized when program starts Destroyed when program ends 11
Default Class Function/Block Variables are automatic Created/Initialized on entry to that function/block Deleted when that function/block ends Override Function Variables by using the static keyword Created/Initialized when the program starts Deleted when the program ends Does not change the scope scope is still inside the function! Global Variables are Static Created/Initialized when the program starts Deleted when the program ends Automatic has no meaning! 12
Example Local Static char * flipflop() { static int flip=1; if (flip) { flip=0; return flip ; } else { flip=1; return flop ; } } for(i=0;i<8;i++) printf( %s,flipflop()); flip flop flip flop flip flop flip flop 13
BAD FORM : Pseudo-Globals It is legal in C to nest a function inside another function This allows the variables in the outside function to be visible (in scope) for the inside function C Coders frown on this practice! Nested functions have other complications Nested functions cannot be re-used It s ugly and confusing 14
Example Nested Functions int main(int argc, char **argv) { char firstargletter(int i) { return argv[i][0]; } int j; for(j=0;j<argc;j++) printf( Arg start: %c\n, firstargletter(j)); return 0; } 15
Enumerations 16
Suppose I have 3 colors of paint RED GREEN BLUE 17
How do I represent these colors in C? I could put the color name in a string char can1[6]; strcpy(can1, green ); if (0==strcmp(can1, red )) printf( First can is red paint ); Takes lots of space Not very clear what is going on 18
How do I represent these colors in C? I could use the first letter R/G/B char can1; can1= G ; if (can1== R ) printf ( First can is red paint ); Takes less space Not very clear what is going on what if I have Grey and Black? 19
How do I represent these colors in C? I could use a number->color mapping 0=red, 1=green, 2=blue char can1; can1=1; if (can1==0) printf ( First can is red paint ); Takes less space Not very clear what is going on was green 2 or 3? 20
C has Enumerations Special C construct to make code clear An enumeration is any finite list of items enum colors { red, green, blue }; 21
C Enumeration Definition Defines a new data type Defines constant values of that type enum colors { red, green, blue }; Define a new type called enum colors Define 3 constants of type enum colors with anonymous values 22
Enumeration Constants Enumeration constants are variable names Cannot use these names for anything else int red=16; 23
C Enumeration Declaration Create a variable with an enumerated type enum colors can1; Type specification enum colors must be defined above Variable name Variable can have any value as long as it s a color enumeration constant. can1=green; 24
Putting it all together enum colors {red, green, blue} can1; can1=green; if (can1==red) printf( First can is red paint ); 25
Why enums? Makes reading the code crystal clear Compiler can check to make sure everything is correct can1=orange; // compiler error orange not a valid color Space efficient Easy to extend 26
Problem: Using enums in messages printf( The value of can1 is %d,can1); The value of can1 is 5 Problem enum values don t really make sense to people! 27
Solution: Provide a function to translate char * colorname(enum colors inc) { switch(inc) { case red : return red ; case green: return green ; case blue: return blue ; } return unknown ; } 28
Printing with a translator function printf( First can has %s paint\n,colorname(can1)); First can has green paint Note update translator function when enum changes! 29
Typedefs 30
Defining New Types Built in types: char, int, float, short int, long int, double, etc. Arrays extended types Pointers extended types Derived types: structures, enums, unions Must include struct lnode or union val_union 31
Derived Types can get Complicated struct lnode* nodelist[10]; nodelist is an array of 10 pointers to lnode structures union val_union **vptrs; vptrs is a pointer to one or more pointers to one or more instances of a val_union union 32
Anatomy of a Typedef typedef struct lnode * nodeptr; Built-In or Derived Type Name New Type Name (Synonym) 33
TypeDef Synonym for Any Type typedef struct lnode * nodeptr; nodeptr head; nodeptr newnode=makelnode(12); 34
Why TypeDef 1. Makes code much more readable It s much clearer to read an write nodeptr than struct lnode * 2. Encapsulate specific sub-types typedef float length_t; length_t atob; length_t btoc; Make this double to change all lengths! 35
Resources Programming in C, Chapter 7 Wikipedia Variable https://en.wikipedia.org/wiki/variable_(computer_science) Programming in C, Chapter 13 (Enumerated Data Types) Wikipedia Enumerated Type https://en.wikipedia.org/wiki/enumerated_type Enumeration Tutorial http://www.programiz.com/c-programming/cenumeration Scope Tutorial http://www.tutorialspoint.com/cprogramming/c_scope_rules.htm Wikipedia Typedef https://en.wikipedia.org/wiki/typedef 36