Variable Storage Classes in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 6.4 Free with a free account

Variable Storage Classes in C

Programming in C · Chapter 6: Functions, Scope, Storage Classes, and RecursionSection 6.4 · lesson 36 of 786 min · free with a free account

← Variable Scope in CNext lesson: Pass by Value vs. Pass by Reference 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

How long C variables live with auto, static, register and extern.

  • Compare the lifetime of auto locals and static locals
  • Explain the default starting value of static and global variables
  • Describe the register hint and its address restriction
  • Use extern to share a global and static to hide one in its file

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 (789 words). Read along, or search it.

Opening Analogy

Credits Reset, High Scores Remain

An arcade machine shows credits, zero, every time you walk up to it. But the high-score board behind the counter remembers the best score from yesterday, last week, even last year. Both are numbers in memory. The difference is how long each one is kept. In C, you choose that with a storage class. Scope, from lesson 6.3, was where a name works. This lesson is about how long the box lives.

auto Versus static

Fresh Boxes Versus Kept Values

Every local you've written so far is an auto variable, short for automatic. C creates its box when the function starts, and discards it at the end. That's why the call stack grows and shrinks. The keyword auto is allowed, but nobody writes it, because it's already the default for locals. Disposable boxes have a catch: each call gets a fresh box, so nothing is remembered from last time. Now put static in front of a local. Its box moves to static storage: set up once before main starts, and kept until the program ends. It's still private to its function, so its scope doesn't change. But it keeps its value between calls. Both functions start count at 0 and add one, and main calls each of them three times. Run it. The auto counter prints 1 every time. The static counter prints 1, 2, 3. The line static int count equals 0 doesn't run on every call. The 0 is placed once, before the program starts. After that, only count plus plus changes it.

Default Values

Static Locals and Globals Start at Zero

A static local with no starting value at all begins at 0. So does a global. That's unlike an ordinary local, whose starting value is leftover garbage, as you saw in lesson 3.2. Run it. total_wins starts at 0, and calls counts 1, then 2.

register

A Speed Hint With No Address

The keyword register asks the compiler to keep a variable in the processor's fastest spot, like a loop counter. It's only a hint, and modern compilers decide this on their own. Used politely, it simply works: the sum of 1 to 100 is 5050. But register brings one hard rule. You can't ask for its address, so the ampersand operator isn't allowed on it. Try it, and clang refuses: address of register variable requested. You'll use ampersand on ordinary variables in lesson 6.5.

Multiple Files

Extern Shares, Static Hides

Big programs live in several .c files. Two keywords control how those files see each other's globals. On the right, tokens.c defines arcade_tokens: the one real box. On the left, main.c says extern int arcade_tokens. Extern means: this variable already exists, and its real box is defined somewhere else. It makes no new box, so both files share one number. Build both files into one program, and run. 500 tokens, and the code check says 1, for yes. Static on a global means the opposite: keep this private to this file. secret_code is static, so only tokens.c can see it. Main reaches for it with extern anyway. Build again, and the linker refuses: undefined symbols, secret_code. The compiler accepted main.c on trust. But the linker, which joins the files, found no visible secret_code to connect it to. A static function is private to its file too. And if two files both define one global, the linker refuses that as well: duplicate symbol.

Summary Table

Four Kinds of Storage Compared

Here are the four kinds together. An auto local lives on the stack for one call, and only its block can use it. A static local lasts the whole run, but only its own function can use it. A global lasts the whole run, and other files can reach it with extern. And a static global lasts the whole run, but stays inside its own file. Register only adds a hint to any of this.

Quick Check

A Static Ticket Counter

Quick check. next_ticket hands out ticket numbers. Its number starts at 100, and each call adds 5. Main calls it three times. What does it print? Pause and predict. Build and run: 105, 110, 115. The static number is set to 100 once, before the program starts. The first call adds 5 and returns 105. The second call finds 105 still there, and adds 5 again. Without static, every call would make a fresh 100, and print 105 three times.

Wrap-Up

Counting Visitors With a Static Local

Back at the arcade, Priya wanted a visitors today counter. As a local, it always showed 1. As a global, any function could reset it. Sam suggested a static local inside the welcome function. It counted correctly, and nothing else could touch it.

Key Takeaways

Storage Classes in Review

To sum up. An auto local gets a fresh box at every call. A static local is set up once, and keeps its value between calls. Register is only a hint, and its address can't be taken. And extern shares one global between files, while static on a global hides it in its file.

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 Storage Classes in C

What is the difference between an auto and a static local variable in C?
An auto local, the default for variables inside a function, gets a fresh box every time the function is called and disappears when it returns. A static local is set up once before main starts and keeps its value between calls, though only its own function can see it. A counter starting at 0 prints 1, 1, 1 as auto but 1, 2, 3 as static.
What is the initial value of a static variable in C?
A static local or a global with no initializer starts at 0. If it has an initializer, the value is placed once before the program starts, not on every call, so static int count = 0; does not reset count each time the function runs. An ordinary local with no initializer holds a leftover garbage value instead, so it must be set before use.
What does the extern keyword do in C?
extern declares that a variable already exists and is defined somewhere else, often in another .c file, without creating a new one. If tokens.c defines int arcade_tokens = 500; and main.c declares extern int arcade_tokens;, both files share one variable. If a global is marked static, it stays private to its file, and the linker reports an undefined symbol when another file reaches for it.
Can you take the address of a register variable in C?
No. The register keyword asks the compiler to keep a variable in the processor's fastest storage, so C forbids applying the & operator to it, and clang reports address of register variable requested. The keyword is only a hint, and modern compilers make this decision on their own. It can be used on local variables and function parameters, such as a loop counter.

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 →