Named Containers for Data: Variables | C++ Programming

UPI Study › Courses › C++ Programming › Free lessons › Lesson 2.5 Free with a free account

Named Containers for Data: Variables

C++ Programming · Chapter 2: Getting Started with C++Section 2.5 · lesson 12 of 84video coming soon

← Representing QuantitiesNext lesson: Putting Data Into Variables →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

What variables do, and why they exist.

  • Explain a variable's name, address and value
  • Write a declaration and say what the compiler does
  • Choose names the language and readers accept
  • Use const for values that must never change

Transcript

Everything said in the video, section by section (1,419 words). Read along, or search it.

Opening Question

How a Program Holds a Number

A program that can't hold on to anything can't do very much. So how does a program hold on to a number? With a variable: a piece of memory the machine sets aside for you, with a name attached. You refer to it by name, without ever knowing where it actually sits.

Why Names

Memory Slots and the Compiler's Trade

A computer's memory is a very long row of numbered storage slots. The number is the only way the hardware tells one slot from another. To keep a running total, the machine reserves some slots, remembers their number, and goes back to that number whenever the total is needed. You could do that bookkeeping yourself, and it would be miserable. The numbers are decided when the program runs, and a wrong number looks as valid as a right one. So the language offers a trade. You supply a name, and the compiler handles the numbers. You write total, and it substitutes the right location every time. The name doesn't survive into the running program in any form the machine consults. But it's the difference between programming and clerical work.

Core Concept

Name, Address, Value, and Type

Every variable has a name, an address and a value. Confusing any two of them causes a lot of early trouble. The name is the word you use in your code. You choose it when you declare the variable, and it never changes. The address is the number of the slot where the data sits. The system decides it when the program runs, and it may differ from run to run. Run this twice. The value is forty both times, but the address changed. The value is the data currently stored there, and your program changes it freely, which is exactly why it's called a variable. And alongside sits the type, fixed at declaration: how much room to reserve, and how to read the bits.

Declaration

Introducing a Name With a Type

Before a name can be used, it must be introduced. That's a declaration: the type, then the name you've chosen, then a semicolon. In int student count, int is the type, saying how much room is needed and how to read the bits. Student count is the name. And the semicolon ends the statement. Leave it out, and it's an error. When the compiler reads that line, it quietly does three things. It sets aside enough memory for one value of that type. It records that the name refers to that memory. And it records the type, so every later use can be checked. An attempt to store something unsuitable there will be reported, rather than allowed through.

Reading Aloud

Declarations Reserve Room, Not Contents

Declarations read naturally aloud. Int item count means: set aside room for one whole number, and call it item count. Double unit price means room for one number with a fractional part. Char grade means room for one character. And bool is complete means room for one true-or-false value. But here's what a declaration does not do. Reserving the room isn't the same as putting something useful in it. A declaration on its own gives you a named space whose contents aren't yet meaningful. Filling it, safely, is the subject of the next section.

Naming Rules

What Makes a Legal Identifier

A name in C++ is called an identifier, and the rules are short. Letters, digits and the underscore, and nothing else: no spaces, hyphens or punctuation. And it may not begin with a digit. Upper and lower case are different: total, with a capital T, and total in lower case are two separate names. It can't be a reserved keyword. And names that start with an underscore, or contain two in a row, are set aside for the language, so avoid them. Here, item count two is fine. Second place fails, because it begins with a digit. Total space score fails, because the space makes two names. Unit dash price fails, because the hyphen is subtraction. And class fails, because it's a keyword. Look at the message for class: it hardly mentions names at all.

Reserved Words

Keywords You Cannot Use as Names

Keywords are the words the language has already claimed. They can't be used as names for anything of yours. There are type keywords, like int, char, bool, double and void. Control flow keywords, like if, else, switch, for, while and return. Structure keywords, like class, struct, namespace and template. And others, like const, new, delete, true, false and sizeof. You don't need to memorize the list. The compiler tells you at once, and any reasonable editor colors them differently. But recognize the common ones on sight.

Good Style

Legal Names Versus Meaningful Names

Everything so far is about legality, and legality is the low bar. A name's real job is to tell the next reader, very often you, months later, what the variable is for. The compiler has no opinion about that. d1, d2, n and flag are all legal, and tell you nothing. Unit price, shipping cost, items in cart and order confirmed say exactly what they hold. Two more habits. Pick one style for multi-word names, camel case or underscores, and keep it throughout a file. And avoid characters that look alike. A lone lowercase l is nearly indistinguishable from the digit one, and a capital O from zero.

Shortcut

Declaring Several Variables Together

When several variables share a type, they can be declared together, with the names separated by commas. Three lines, or one: either way you get the same three variables, each with its own memory. The type is written once, and applies to every name. Compactness is the argument for it. But a long combined declaration is easy to misread, and easy to break when someone adds a name. So combine only closely related variables, like the three dimensions of a box. Otherwise, give each its own line.

Constants

Fixed Facts With const

Not everything a program holds is meant to vary. A tax rate, the days in a week, or the maximum entries a table accepts are fixed facts. Put const at the front of a declaration, and the name becomes a named constant. It must get its value right there, because there's no later chance. Compare a bare one point one eight in the middle of a calculation, a magic number, with tax rate. The named version explains itself. It gives one place to change. When the rate changes, you edit one line, instead of hunting for every copy, and typing one point eight in one of six places can't happen. And the compiler enforces it. Try to change the rate later, and the build stops. Capitals with underscores is a convention, not a rule, but it shows at a glance what can't change. And const is preferred over C's preprocessor constants, because it has a type.

Under the Hood

How Much Memory Each Type Takes

It's worth picturing what's physically happening. Each variable occupies a definite amount of memory, set by its type. A char takes the smallest addressable unit, one byte. An int typically takes four, and a double typically takes eight. Sizeof reports it. Two variables never share the same memory, and each sits at an address that stays put for as long as it exists. Two consequences follow. The room a type is given decides the range of values it can hold. That's why a whole-number type has a largest value. And because each variable has an address, addresses themselves can be taken, stored, and used to reach the variable indirectly. That comes later.

Quick Check

The Capital Letter That Breaks the Build

Quick check. This program declares int item count, then assigns to item count with a capital I. What happens when you build it? Pause and predict. It doesn't build. To the compiler, the capitalized name is a different, undeclared name. The message is baffling at first, because the name is plainly there, two lines up. Clang helps by suggesting the fix, but not every compiler does.

Common Mistakes

Keyword Names, Duplicates, and Changing const

A few more mistakes are worth expecting. Using a keyword as a name gives an error that points at perfectly ordinary-looking code, as you saw with class. Declaring the same name twice is an error, not a replacement. And once a name is const, nothing may change it. That's the whole point, and occasionally a surprise.

Key Takeaways

Variables, Declarations, and Good Names

To summarize. A variable has a name, an address and a value, and a type fixed when it's declared. The name is for you, the address is for the machine, and the value is what the program works with. A declaration reserves room, records the name, and lets every later use be checked. But it doesn't put a meaningful value there. Legal names are the low bar. Choose names that say what the variable holds. And use const for fixed facts, so they explain themselves, change in one place, and are enforced by the compiler.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
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

C++ Programming 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 Named Containers for Data: Variables

What is the difference between a variable's name, address, and value in C++?
A variable's name is the word you write in code, its address is the number of the memory slot where the data sits, and its value is the data currently stored there. The name stays the same, the system picks the address when the program runs, and the program can change the value freely. The type is fixed at declaration.
What does the compiler do when it reads a variable declaration like int studentCount;?
The compiler does three things when it reads that declaration. It sets aside enough memory for one int, records that the name studentCount refers to that memory, and records the type so every later use can be checked. A declaration reserves room but does not put a meaningful value there.
What are the rules for a legal variable name (identifier) in C++?
An identifier may contain only letters, digits, and underscores, and it cannot start with a digit. It cannot be a reserved keyword such as class or int. Names are case sensitive, so total and Total are different. Avoid names starting with an underscore or containing two underscores in a row, since those are set aside for the language.
Why and how do you use const for a variable in C++?
Put const at the front of a declaration, such as const double TAX_RATE = 1.08;, to make a named constant for a value that must not change. It must be given its value in that declaration. A named constant explains itself, gives one place to edit, and makes the compiler stop the build if code tries to change it.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) 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 C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 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 C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 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 C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →