UPI Study › Courses › Programming in C › Free lessons › Lesson 6.3 Free with a free account
Variable Scope in C
Programming in C · Chapter 6: Functions, Scope, Storage Classes, and RecursionSection 6.3 · lesson 35 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Variable Storage Classes in C →← C Standard Library OverviewNext lesson: Variable Storage Classes in C →
In this lesson
Where a variable's name can be used in a C program.
- Distinguish file scope, function locals and inner block scope
- Explain shadowing and which declaration a line uses
- Pass values through parameters instead of reaching into another function
- Explain why local variables are safer than globals
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (973 words). Read along, or search it.
Opening Analogy
Keys That Open One Room
In the arcade, the key to the prize room opens the prize room, and nothing else. The ticket counter has its own cash drawer, and the repair shop has its own tools. Nobody grabs something from a room they're not standing in. C variables work the same way. Each name works only in certain places, and the rule for where a name works is called scope.
Scope Levels
Global, Local and Block Variables
A name's scope is the part of the program where it can be used. C builds scopes like rooms inside a building. A block is any code between a pair of curly braces: a function body, the inside of an if, or the body of a loop. A variable made inside a block belongs to that room. It exists from its declaration on, and at the closing brace, the room closes. arcade_tokens sits outside every function. It has file scope, so every function below it can use it. It's called a global variable. games lives in main, and copy lives in show_tokens. Only their own function sees them. Variables like these are called local variables. And discount exists only between the braces of the if. That's the innermost room. Run it. The block took 20 off, so show_tokens sees 80, and so does main. A line can use names from its own room, and from every room around it. Never from a room inside it, or beside it.
Terminology
Block Scope Versus Function Scope
So a variable can live in three places: at file level, inside a function, or inside an inner block. One detail about the words. The C standard counts a function's body as a block too, so its locals and parameters officially have block scope. In the standard, function scope means something else. It covers only labels for goto. Many books use the phrase loosely, for locals.
Common Error
Using a Name From Another Function
What if a line reaches for a name from a room it isn't in? Priya's print_status tries to show the tokens that belong to main. Build it. Clang stops: use of undeclared identifier tokens. In plain words: I've never heard of tokens in this room. There is a tokens in main, but that room is closed to print_status. GCC says the same thing in its own words: tokens undeclared. The fix is to hand the value in, through a parameter. print_status takes an int named tokens, and the call passes main's tokens. Build and run. Main has 8 tokens, and print_status now shows 8 too. That parameter is print_status's own tokens, holding a copy of main's. You'll see why copies matter in lesson 6.5.
Shadowing
The Nearest Declaration Wins
Rooms can hold names that already exist outside. Here, a global is called score, and main declares its own score too. C allows it. The inner name shadows, or hides, the outer one while you're inside its room. The rule: a line uses the nearest declaration, looking outward from where it stands. And only declarations above it count. Watch it run. The first line in main reads the global, 10, because main's own score isn't declared yet. Then main's score, 99. Inside the inner block, a third score, 5. After the brace, main's 99 is back. And show has no score of its own, so it reads the global: 10.
Compiler Flag
Catching Shadowed Names With -Wshadow
Shadowing is legal, so wall and W extra stay silent. And a change can seem not to stick. Here, the if declares a second tokens. Build with the usual flags: no warning. Inside prints 100, and outside prints 8. Now add W shadow, which isn't part of the usual two. Clang reports: declaration shadows a local variable, and points to the first one. When it does, rename one of the two variables.
Design Advice
Why Globals Are Risky
A global is tempting. Every function can use it, with no parameters to pass. But look at what that means. play_game adds one to games_played, and play_two calls it twice. Run it: games played, 3. Nothing in play_game's header says it changes anything outside itself. In a big program, a wrong count could come from any function. Locals are safer, because only their own function can touch them.
Quick Check
A Global and a Local Named Lives
Quick check. A global named lives starts at 3. lose takes away one life. Main declares its own lives, 9, then calls lose twice. What does it print? Pause and predict. Build and run: lives, 9. lose has no lives of its own, so it changes the global, from 3 down to 1. Main's printf uses the nearest declaration, main's own lives. Nobody touched it, so it's still 9. Two variables, one name, and a change that doesn't seem to stick. That's exactly the trap W shadow points out.
Quick Check
A Variable Gone After Its Block
One more. A player gets a bonus of 20 inside an if. After the closing brace, main prints both numbers. What happens? Pause and predict. Build it. Clang stops: use of undeclared identifier bonus. The variable was thrown away at the closing brace. Its room closed before the printf. If you need a value after a block, declare the variable before the block, in the outer room. Declare bonus above the if, set it inside, and the program prints 24 and 20. Same numbers, one line moved up a room.
Wrap-Up
A Negative Token Total Traced
Back at the arcade, Sam reported that the token total sometimes went negative. It was a global, so any of twelve functions might be the cause. Priya made it a local in main, and passed it only to the few functions that needed it. The bug had nowhere left to hide. Her rule: a global for a fixed fact, like a price list. Changing values travel as parameters.
Key Takeaways
Scope in Review
To sum up. Scope is where a name can be used: file level, a function, or an inner block. A name declared in a block ends at its closing brace. When two names match, the nearest declaration above the line wins. That's shadowing. And prefer locals. Pass changing values in as parameters.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Variable Scope in C
What is variable scope in C?
What is variable shadowing in C?
Why do I get use of undeclared identifier for a variable declared in another function?
Why are global variables considered risky in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →