Variable Declaration in C, Explained with Code Examples

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

Variable Declaration in C

Programming in C · Chapter 3: Data Types, Variables, Math Library, and Console I/OSection 3.2 · lesson 14 of 786 min · free with a free account

← Complete Data Type Reference in CNext lesson: Variable Assignment and Typecasting 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

Declare and name variables correctly and give each one a starting value.

  • Write variable declarations with a type, a name and an optional starting value
  • Apply C's rules for legal identifiers and good naming habits
  • Interpret compiler errors for bad names and undeclared identifiers
  • Explain why uninitialized variables are dangerous and how to avoid them

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

Opening Mystery

Same Code, Different Totals

Priya's token counter worked perfectly on her laptop. On Sam's computer, the same program showed strange totals. Same code, same compiler options, different answers. By the end of this lesson, you'll know why, and the one tiny fix. It starts with how a program asks for a place to keep a value.

Declarations

Type, Name and Starting Value

A variable is a named place in memory that holds one value, and the value can change while the program runs. Think of an arcade locker with a name on the door. A declaration is the line that creates it. The pattern: the type, then the name, then optionally equals and a starting value, then a semicolon. When the compiler reaches a declaration, it reserves enough memory for that type, and attaches your name to it. A shortcut: several variables of one type can share a declaration, separated by commas. Run it, and every value comes back. Both lines match the starting values.

Identifier Rules

Letters, Digits and Underscores

A name you invent is an identifier, and C has strict rules for them. Break one, and the compile stops. A name may use letters, digits and the underscore. It may not start with a digit. It may not contain spaces or symbols, like a dash. And it may not be a keyword: a word C keeps for its own grammar, like int, return or while. Upper and lower case are different letters, so score with a small s and Score with a capital are two separate variables.

Error Message

A Name Starting With a Digit

Here's what Clang says about a name that starts with a digit. Two errors, and both are confusing. C reads 1st prize as a number with a strange ending. So it first complains that it expected a name, then that s t prize is an invalid suffix on an integer constant. When you see invalid suffix on an integer constant, look for a name that starts with a digit. GCC reports the same mistake in its own words.

Naming Habits

Snake Case and Reserved Names

Legal isn't the same as good. Say what the value holds: tokens left beats t l, and distance beats x. Join words with underscores, in lowercase. That's snake case, the common style in C. Write fixed values in capitals, like MAX PLAYERS. And never start a name with an underscore and a capital letter, or with two underscores. C reserves those for the compiler's own use.

Quick Check

Which Top Score Name Compiles

Quick check. Priya needs a variable for the top score. She tries three declarations, one at a time. Which one compiles? Pause and predict. The third one. Top score two uses only letters, digits and underscores, and it starts with a letter. A digit at the end is fine. Two top score starts with a digit, so it fails like 1st prize. And the dash in the first one is a minus sign to C.

Error Message

A Dash Read as a Minus Sign

Watch what Clang makes of the dash. It reads top, minus score, and expects the declaration of top to end right there, before the minus. So the error says expected semicolon at end of declaration, with the caret at the dash.

Declaration Order

Declare Before You Use

C reads your file from top to bottom, like a person reading a page. A name exists only from the line where it's declared. Here, the printf call uses tokens on line 4, but tokens is declared on line 5. Clang stops: use of undeclared identifier tokens. Swap the two lines, and it compiles and runs. In C, the order of lines matters.

Uninitialized Variables

Leftover Values in Memory

What's inside a locker you've just been handed? Not nothing: whatever the last person left. A new int is the same. The compiler reserved the memory, but didn't clear it. A variable declared without a value is uninitialized, and reading it gives an unpredictable number. With dash Wall, Clang notices. Variable lives is uninitialized when used here. And a note shows the cure: equals zero. But a warning doesn't stop the build. The program is made, and it runs. That's exactly why it's dangerous: the answer means nothing. Treat every warning as something to fix.

The Cure

Start Every Variable With a Value

The cure is a habit: give every variable a starting value when you declare it, even if it's just zero. Now lives starts at three, the build is clean, and adding one gives four. Always start with a value.

Quick Check

Which Variable Clang Warns About

Quick check. This program declares three variables, and gives a starting value to only one of them. Clang warns about exactly one variable. Which one? Pause and predict. Points. It's read, in points plus ten, before anything was put in it. Level also started empty, but line 7 fills it before anyone reads it, so there's nothing to warn about. And lives was filled at once.

Story Ending

One Equals Zero Fixed It

Back to Priya's token counter. You never set it before adding, Sam said, pointing at the dash Wall warning she had scrolled past. On her laptop, the leftover memory happened to look harmless. On Sam's it didn't. One equals zero fixed it everywhere.

Key Takeaways

Declare, Name and Initialize

To recap. A declaration gives a type, a name, and usually a starting value, and the compiler reserves memory for it. Names use letters, digits and underscores, never start with a digit, and are never keywords. Declare before you use, and initialize every variable, because a warning still builds a program.

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 Declaration in C

What are the rules for variable names in C?
A C variable name, or identifier, may contain letters, digits and underscores, but it cannot start with a digit, contain spaces or symbols such as a dash, or be a keyword like int or while. Case matters, so score and Score are different variables. Names that start with an underscore and a capital letter, or with two underscores, are reserved for the compiler and library.
What value does an uninitialized variable have in C?
An uninitialized local variable has no defined value; reading it gives whatever happened to be left in that memory. The compiler reserves space but does not clear it, so the same program can print different results on different computers. With -Wall, Clang warns that the variable is uninitialized when used, but it still builds the program. Giving every variable a starting value, even 0, prevents the problem.
What does use of undeclared identifier mean in C?
Use of undeclared identifier means the code uses a name the compiler has not yet seen declared. C reads a file from top to bottom, and a name exists only from the line where it is declared. If printf uses tokens on line 4 but tokens is declared on line 5, Clang stops with this error. Moving the declaration above the first use fixes it.
How do you declare several variables in one line in C?
Several variables of the same type can share one declaration, separated by commas, as in int lives = 3, level = 1;. The compiler reserves memory for each one and attaches each name to it. Each variable needs its own starting value, though. In int a, b = 0; only b starts at zero, and a is left uninitialized, which is an easy mistake to miss.

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 →