Skip to main content

Section 3.2 Declaring Variables

At a fundamental level, the task of every program is to perform computations that manipulate data. In C++, and many other programming languages, variables are a critical part of this work. A variable is a named location in memory that stores a value. Values may be numbers, text, images, sounds, and other types of data. To store a value, you first have to declare a variable:
int age; // declare the variable age
This statement is called a declaration, because it declares that the variable age has the type int. Each variable has a type that determines what kind of values it can store. For example, the int type can store integers (whole numbers) like 1 and -5.
By itself, a declaration does not have any visible effect. It simply instructs the program to reserve some space in memory and assigns that space a name. As far as a programmer is concerned, the computer memory is a long sequence of numbered locations. Each location typically stores one byte - a sequence of eight digits, each of which is either 0 or 1. To picture what the code above is doing, you should imagine that something like the image below:
Four bytes of memory with random 1’s and 0’s.
Figure 3.2.1. Declaring int age asks to reserve four bytes of memory.
Once that memory is reserved, any use of the name age will tell the compiler we are referring to that memory. The type int tells the compiler two things: how much memory to reserve (different types require different amounts of space) and how to interpret the 1’s and 0’s. In this case the compiler will interpret them as an integer. If we were storing a decimal number, or a piece of text, we would need to tell the compiler to interpret the bits differently. (For deeper coverage of representing different kinds of data using bits, see Welcome to CS Data Representation chapter)

Checkpoint 3.2.1.

You have attempted of activities on this page.