Search

1.3 — Introduction to variables

Data

In lesson 1.1 -- Statements and the structure of a program, you learned that the majority of instructions in a program are statements, and that statements are grouped into functions. These statements perform actions that (hopefully) generate whatever result the program was designed to produce.

But how do programs produce results? They typically do so by manipulating (reading, changing, and writing) data residing in the computer’s memory. Broadly defined, data is any sequence of symbols (numbers, letters, etc…) that can be interpreted to mean something. For example, when you examine a thermometer to see whether you’re running a fever, the resulting temperature is data, being interpreted by you.

Similarly, our programs can work directly with certain kinds of data. In the Hello world program from the aforementioned lesson, the “Hello world!” text that the program sent to the monitor for display was data.

In this lesson, we’ll take our first look at basic data handing in C++.

Memory and variables

All computers have memory, called RAM (random access memory), that is available for your programs to use. You can think of RAM as a series of mailboxes that can be used to hold data while the program is running. A single piece of data, stored in memory somewhere, is called a value.

In some older programming languages (like Apple Basic), you could directly access these mailboxes (a statement could say something like go get the value stored in mailbox #7532).

In C++, direct memory access is not allowed. Instead, we typically work with objects. A object is a region of storage (usually memory) that we can use to store values. Objects have a few other properties as well (that we’ll mostly cover in future lessons), but the important thing to note is that the compiler takes care of where objects get put in memory, so we generally don’t have to worry about it. Instead, we can just create objects, give them values, use those objects as we please, and not worry about memory much at all!

An object that has an explicit name is called a variable. Most of the objects we create in our programs will be variables.

Variables and instantiation

In order to create a variable, we use a special kind of declaration statement called a definition (we’ll clarify the difference between a declaration and definition later).

Here’s an example of defining a variable named x:

At compile time, when the compiler sees this statement, it makes a note to itself that we are defining a variable, giving it the name x, and that it is of type int (more on types in a moment). A variable’s name also called an identifier, as that is how the variable will be identified. From that point forward (with some limitations that we’ll talk about in a future lesson), whenever the compiler sees the identifier x, it will know that we’re referencing this variable.

When the program is run (called runtime), the variable will be instantiated. Instantiation is a fancy word that means the variable will be assigned a memory address. Variables must be instantiated before they can be used to store values. For the sake of example, let’s say that variable x is instantiated at memory location 140. Whenever the program then uses variable x, it will access the value in memory location 140.

Data types

So far, we’ve covered that variables are a named region of storage that can store a data value (how exactly data is stored is a topic for a future lesson). A data type (more commonly just called a type) tells the compiler what type of value (e.g. a number, a letter, text, etc…) the variable will store.

In the above example, our variable x was given type int, which means variable x will represent an integer value. An integer is a number that can be written without a fractional component, such as 4, 27, 0, -2, or -12. For short, we can say that x is an integer variable.

In C++, the type of a variable must be known at compile-time (when the program is compiled), and that type can not be changed without recompiling the program. This means an integer variable can only hold integer values. If you want to store some other kind of value, you’ll need to use a different variable.

Integers are just one of many types that C++ supports out of the box. For illustrative purposes, here’s another example of defining a variable using data type double:

C++ also allows you to create your own user-defined types. This is something we’ll do a lot of in future lessons, and it’s part of what makes C++ powerful.

For these introductory chapters, we’ll stick with integer variables because they are conceptually simple, but we’ll explore many of the other types C++ has to offer soon.

Defining multiple variables

It is possible to define multiple variables of the same type in a single statement by separating the names with a comma. The following 2 snippets of code are effectively the same:

is the same as:

When defining multiple variables this way, there are two common mistakes that new programmers tend to make (neither serious, since the compiler will catch these and ask you to fix them):

The first mistake is giving each variable a type when defining variables in sequence.

The second mistake is to try to define variables of different types in the same statement, which is not allowed. Variables of different types must be defined in separate statements.

Best practice

Although the language allows you to do so, avoid defining multiple variables in a single statement (even if they are the same type). Instead, define each variable in a separate statement (and then use a single-line comment to document what it is used for).

Summary

In C++, we use variables to access memory. Variables have an identifier, a type, and a value (and some other attributes that aren’t relevant here). A variable’s type is used to determine how the value in memory should be interpreted.

In the next lesson, we’ll look at how to give values to our variables and how to actually use them.

Quiz time

Question #1

What is data?

Show Solution

Question #2

What is a value?

Show Solution

Question #3

What is a variable?

Show Solution

Question #4

What is an identifier?

Show Solution

Question #5

What is a type?

Show Solution

Question #6

What is an integer?

Show Solution


1.4 -- Variable assignment and initialization
Index
1.2 -- Comments

152 comments to 1.3 — Introduction to variables

  • Hi guys, have a problem and i dont know how to solve it:

    i copy/pasted the "Enter a nuber" program, so i ran it and it was ok, but then i entered a number, pressed Enter and it showed me this:

    'short program 0.exe': Loaded 'C:\Visual Studio 2005 Projects\short program 0\debug\short program 0.exe', Symbols loaded.
    'short program 0.exe': Loaded 'C:\Windows\System32\ntdll.dll', No symbols loaded.
    'short program 0.exe': Loaded 'C:\Program Files\AVAST Software\Avast\snxhk.dll', No symbols loaded.
    'short program 0.exe': Loaded 'C:\Windows\System32\kernel32.dll', No symbols loaded.
    'short program 0.exe': Loaded 'C:\Windows\System32\KernelBase.dll', No symbols loaded.
    'short program 0.exe': Loaded 'C:\Windows\winsxs\x86_microsoft.vc80.debugcrt_1fc8b3b9a1e18e3b_8.0.50727.42_none_ef74ff32550b5bf0\msvcr80d.dll', No symbols loaded.
    'short program 0.exe': Loaded 'C:\Windows\System32\msvcrt.dll', No symbols loaded.
    'short program 0.exe': Loaded 'C:\Windows\winsxs\x86_microsoft.vc80.debugcrt_1fc8b3b9a1e18e3b_8.0.50727.42_none_ef74ff32550b5bf0\msvcp80d.dll', No symbols loaded.
    The program '[2556] short program 0.exe: Native' has exited with code 0 (0x0).

    And btw im using visual C++ 2005 Express Edition.

  • edvinoske

    How do I copy and paste code in my ide without ruining it ?

  • blankie

    hi, i'm using Borland C++(ver 5.1) and i was wondering if anyone know's what is the command or equivalent for "cin" there, i know that cout is "printf" could "cin" be scanf, if anyone know's please help

  • usman khalid

    Question 1: Write Fibonacci sequence program. Take input from user then print the Fibonacci sequence to 10 Steps

    Question 2: Write a program which will get a character array from user and search any character from that array

    what is the program of these questions plz help

  • Sam

    I copied and pasted this program into Visual Studio 2010 (and un-commented line 1):

    //#include "stdafx.h" // Uncomment this line if using Visual Studio
    #include <iostream>

    int main()
    {
    using namespace std;
    cout << "Enter a number: "; // ask user for a number
    int x;
    cin >> x; // read number from console and store it in x
    cout << "You entered " << x << endl;
    return 0;
    }

    When I run the program, it closes as soon as I hit "enter" when I've typed a number. I tried using cin.get() to prevent this, but it keeps happening. How can I fix this?

  • master987124

    how to run your program without using microsoft visual C++ ?

  • mayur13

    sorry i got my mistake

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">