Variable Scope in C, Explained with Code Examples

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

← C Standard Library OverviewNext lesson: Variable Storage Classes in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Scope is the part of a program where a name can be used. A variable declared outside every function has file scope and is a global; one declared inside a function or an inner block is a local with block scope. A local exists from its declaration to its closing brace, and a line can use names from its own block and from the blocks around it.
What is variable shadowing in C?
Shadowing happens when an inner block declares a name that already exists outside, such as a local score in main when a global score exists. Inside the inner block, the inner name hides the outer one, because a line uses the nearest declaration above it. Shadowing is legal, so -Wall and -Wextra stay silent, but clang's -Wshadow flag reports it.
Why do I get use of undeclared identifier for a variable declared in another function?
A function's locals are visible only inside that function, so other functions cannot reach them by name. If main declares tokens and print_status tries to print tokens, clang reports use of undeclared identifier. The fix is to pass the value in through a parameter, such as void print_status(int tokens), and call print_status(tokens). The parameter then holds a copy of main's value.
Why are global variables considered risky in C?
Any function can change a global, and nothing in a function's header shows that it does. In a large program, a wrong value could come from any function that touches the global, which makes bugs hard to trace. A local is visible only in its own function, so far fewer places can change it. A common rule is globals for fixed facts, like a price list, and parameters for changing values.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →