Concepts / Declaring Variables in C++

Declaring Variables in C++

The >> operator reads data from the standard input stream cin into the variable on its right.

  • Programming

Why a Program Needs Named Data

A program that needs data from the user has to pull that data from somewhere. In C++, the place it pulls from is the standard input stream, and the tool that moves data out of that stream and into a variable is the >> operator. Starting from a concrete question makes the rest of the article easier to follow: when a program reads a number into a variable, what decides which value ends up stored there, and how would you find the line responsible if the stored value were wrong?

Before a program can use a piece of data, it needs a way to refer to that data by name. A variable is the everyday tool for this, and declaring a variable is the step that brings it into existence in the program. This article moves in small steps. First you will watch a read move data from the input stream into a variable. Then you will see what a declaration supplies and what the program holds in memory once that declaration has happened. Each step is a change in state, so you can see what is present before and after it.

Following One Read from Input to Variable

Think of a single read as a path with four stations. Characters arrive on the standard input. The cin stream holds them. The >> operator takes what the stream provides. The target variable is the place where the result is kept. The variable is the only station on this path that changes as a result of the read. The stream is not emptied into a new place in your program; the operator transfers what it takes into the variable.

Characters onstandard inputwhat the user typescin streamholds the characters>> operatortakes what the streamprovidesTarget variablewhere the result is keptarriveprovidesstores result
How does data move from the standard input stream into the variable on the right of >>, and what happens at each step?

The statement is read from left to right the way the operator suggests. The stream cin is the source, the operator >> is the transfer, and the variable named on the right is the target. Here the stream is always written on the left and the destination on the right. Many beginners expect assignment to flow from right to left, so this layout can feel reversed at first. Keeping the direction straight is the first habit to build.

How the Target Type Decides What Is Accepted

The most important fact about >> is that the type of its right-hand operand determines two things at once: what kind of input is accepted, and what the target of the input operation is. The operator does not have one fixed behavior. It reads according to the variable you give it. The same statement form, cin >> something, can read an integer or a floating-point number depending on how that something is declared.

cpp
Notes on the code
  • int count; declares an integer variable, so this read targets an int
  • cin >> count; reads integer input such as 1234 into count
  • double price; declares a double-precision variable, so this read targets a double
  • cin >> price; reads floating-point input such as 12.34e5 into price
Target declared asKind of input acceptedExample input from the source
intInteger input1234
doubleDouble-precision floating-point input12.34e5

The declared type of the target controls which input the read accepts. The operator and the stream are the same in both rows.

Setting the two reads side by side makes the pattern clear. The operator and the stream are identical in both cases. Only the target type changes, and with it the kind of number that the read accepts. This is why the declared type of the variable is the first thing to check when a read looks wrong: it governs what the >> operator will attempt to accept.

Tracing Two Reads Line by Line

The source uses a pair of reads that combines both target types. Work through them as a trace, one line at a time, asking at each step what the operator is reading from and what it is writing into. The trace below uses the declarations and input from the previous section.

Worked example

Tracing count and price

The program declares an int named count and a double named price, then reads 1234 into count and 12.34e5 into price. What does each variable hold after its read?

  1. 1
    Declare count

    int count; introduces the name count and specifies that it is an integer variable. No input has been read yet, so the value is not yet determined by any read.

  2. 2
    Declare price

    double price; introduces the name price and specifies a double-precision floating-point type.

  3. 3
    Read into count

    cin >> count; takes the characters 1234 from the stream. Because the target is an int, the operator accepts integer input, so count holds 1234.

  4. 4
    Read into price

    cin >> price; takes 12.34e5 from the stream. Because the target is a double, the operator accepts floating-point input, so price holds 12.34e5, which is 1234000.

Result

count holds 1234 and price holds 1234000. The operator and the stream were the same in both reads; only the target type changed.

What do you think happens?

You declare int inch; then run cin >> inch; and type 12. What does inch hold after the read?

  • 12

  • inch is empty

  • 0

Reveal answer
Answer:

12

The target is an int, so the operator accepts the integer input 12 from the stream and stores it in inch.

What a Declaration Introduces

Definition

A declaration is a statement that introduces a name into the program and specifies a type for the named entity.

A declaration does two jobs at once. The first job is to introduce a name, so that the rest of the program can refer to the entity by that name. The second job is to specify a type, so that the entity has a defined kind. The type tells the program which values the entity can hold and which operations can be performed on it.

The source material gives a concrete case: a declaration specifies that inch is of type int. In other words, inch is an integer variable. The name is inch, the type is int, and the declaration tells the program that anything called inch holds integer values. Declaring int inch; creates an integer variable called inch.

intthe type: integer valuesinchthe name: refers to theentity;ends the statement
In a declaration like int inch;, which part is the type, which is the name, and what does each one contribute?

Read the statement as two pieces of information. The word int names the type, and the word inch names the entity. Swapping the order, or leaving out the type, would not give the same meaning, because the type is what the declaration is required to specify.

Object, Value, Type, and Variable

Definition

A type defines a set of possible values and a set of operations for an object.

Definition

An object is memory that holds a value; a value is a set of bits interpreted according to a type.

Definition

A variable is a named object, so declaring int inch; creates an integer variable called inch.

These four terms describe different parts of what a declared name refers to. The variable is a named object. The object holds a value. The value is a set of bits, and the type determines how those bits are interpreted. Reading the connections from the variable name downward gives the chain from name to meaning.

Variablea nameObjectmemory that holds a valueValuea set of bitsTypeinterprets the bitsis a namedholdsinterprets
How are the object, its stored value, its type, and the variable name connected to one another?

The declaration itself does not describe the stored bits. It establishes the name and the type. The memory and its value belong to the object the name refers to, and the type determines how that value is read.

Program State Before and After a Declaration

Trace the program's state across the declaration of inch. Before the declaration, the program has no entity called inch, so the name is not yet available for the rest of the program to use. After the declaration, the name inch refers to an integer variable, which is an object with a type. The new named entity is the element that has changed.

inchname introduced by thedeclarationInteger variablean object, held at a memorylocationinttype specified for the namerefers totypes
What does program memory look like before a declaration, and what changes once the name and type are introduced?

Notice what this diagram does not show. The declaration establishes the name and the type. The bits themselves are part of the object that the name refers to, and their meaning comes from the type. A declared variable therefore exists as a named, typed object before any read gives it a value.

Mistakes Beginners Make with Reads

Most errors with the >> operator come from reading its direction or its target incorrectly. The following mistakes are the ones to check first when a read seems to produce the wrong result.

  • Common mistake

    Reading the statement right to left, as if it were assignment

    What it looks like

    Reading cin >> count as if count were the source and the stream were the destination

    Why it fails

    The stream is the source and the variable on the right is the target. The layout is the reverse of assignment as many beginners expect.

    Do this instead

    Read the statement as stream, then operator, then target: cin, then >>, then the variable.

  • Common mistake

    Ignoring the declared type of the target

    What it looks like

    Expecting a double-style value such as 12.34e5 to be stored in an int

    Why it fails

    The type of the right-hand operand decides what input is accepted, so an int target accepts integer input such as 1234.

    Do this instead

    Check the declaration of the variable first, because it governs what the read will attempt to accept.

  • Common mistake

    Assuming the read changes something other than the variable

    What it looks like

    Expecting the stream or the operator to hold the result after the read

    Why it fails

    The variable is the only part of the path that changes as a result of the read.

    Do this instead

    After a read, inspect the target variable to find the stored result.

Finding the Line Where a Value Goes Wrong

When the trace for a program disagrees with your prediction, the goal is to locate the statement where the two first part ways. For reads with the >> operator, the most useful sequence is fixed and short.

  1. 1
    Check the target declaration first, because it determines what the read accepts and what it targets.
  2. 2
    Check the read statement second, confirming that the stream is on the left and the target variable is on the right.
  3. 3
    Check the value the variable holds afterward, comparing it with your prediction.
  4. 4
    The first line where your prediction and the stored value differ is the line to examine.

Checking Your Own Read

EASY

A program declares double weight; and then runs cin >> weight;. Predict what kind of input weight accepts, and name the one value from the earlier example it would store correctly. Then state which line you would check first if weight held an unexpected value.

Hints
  • The declared type of the target controls what input is accepted.
  • The earlier example used 12.34e5 as floating-point input for a double target.
  • Check the target declaration before the read statement.

Key Takeaways

  • The >> operator reads data from the standard input stream cin into the variable on its right, and the stream is always on the left and the target on the right.
  • The type of the right-hand operand determines what input is accepted and what the target of the read is: an int accepts integer input such as 1234, and a double accepts floating-point input such as 12.34e5.
  • A declaration introduces a name into the program and specifies a type for the named entity; declaring int inch; creates an integer variable called inch.
  • A variable is a named object, an object holds a value, and a value is a set of bits interpreted according to a type.
  • When a read gives a surprising value, check the target declaration, then the read statement, then the value the variable holds afterward.

Related concepts

More concepts starting with D