CS156: Intro to C, Part I

Spring 2018

Scope

See this page as a slide show

CS156 Scope

The Scope of Variables

An Example

    int glow;              // a global scope variable
    int main() {
       int loco = 1;       // a local scope var with
                           // valid scope in main
       glow = 2;
       {                   // braces introduce a new scope
          int engineer;    // a variable in this scope
          engineer = loco; // accessing a local
          glow = 3;        // accessing a global
       }
       engineer = 2;       // ERROR: variable not in scope 
       return 0;
    }

Variable Names and Scope

int main() {
   int n = 111;
   printf("n = %d\n", n);
   {
      int n = 222;
      printf("n = %d\n", n);
   }
   printf("n = %d\n", n);
   return 0;
}
n = 111
n = 222
n = 111

Some Tips on Scope

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2016-07-03T16:56

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building