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 actually produce results? They do so by manipulating (reading, changing, and writing) data. In computing, data is any information that can be moved, processed, or stored by a computer.

Key insight

Programs are collections of instructions that manipulate data to produce a desired result.

A program can acquire data to work with in many ways: from a file or database, over a network, from the user providing input on a keyboard, or from the programmer putting data directly into the source code of the program itself. In the “Hello world” program from the aforementioned lesson, the text “Hello world!” was inserted directly into the source code of the program, providing data for the program to use. The program then manipulates this data by sending it to the monitor to be displayed.

Data on a computer is typically stored in a format that is efficient for storage or processing (and is thus not human readable). Thus, when the “Hello World” program is compiled, the text “Hello world!” is converted into a more efficient format for the program to use (binary, which we’ll discuss in a future lesson).

Objects and variables

All computers have memory, called RAM (short for 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 number 7532).

In C++, direct memory access is not allowed. Instead, we access memory indirectly through an object. An object is a region of storage (usually memory) that has a value and other associated properties (that we’ll cover in future lessons). When an object is defined, the compiler automatically determines where the object will be placed in memory. As a result, rather than say go get the value stored in mailbox number 7532, we can say, go get the value stored by this object and the compiler knows where in memory to look for that value. This means we can focus on using objects to store and retrieve values, and not have to worry about where in memory they’re actually being placed.

Objects can be named or unnamed (anonymous). A named object is called a variable, and the name of the object is called an identifier. In our programs, most of the objects we create will be variables.

Author's note

In general programming, the term object typically refers to a variable, data structure in memory, or function. In C++, the term object has a narrower definition that excludes functions.

Variable 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). 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 object will be created and 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. An instantiated object is sometimes also called an instance.

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

374 comments to 1.3 — Introduction to variables

  • Rachel

    What does this mean in simpler terms?
    When an object is defined, "the compiler handles the association of that object to a region of memory."

    Does it just mean - after defining an object, the compiler will place it to a region of memory.

  • NamelessName

    Hey Alex, just wanted to point out a typo at the top section the last sentence says "In this lesson, we’ll take our first look at basic data handing in C++." just a spelling error on the word handling

    Edit: Is there a public offical github repo we can potentially help aid in these types of efforts? (it being spelling errors or improvement to tutorial series ect..)

    • Alex

      Thanks for pointing out the error.

      I don't have a github -- not sure how that would work since this site is based on WordPress and WordPress acts as its own self-contained CMS.

      For now, you can just leave comments on the appropriate article and I'll read them.

  • Rhylee

    Does data basically mean the result of something? Like an experiment result orrr? I understand what you said about the examples (thermometer temperature result). But then it comes to programming, you said the program worlds "hello world" was the data. Im still not too sure how data is defined. If you could possibly explain it a little further for me to understand

    • Alex

      Data doesn't need to be the "result" of anything -- in the context of programming, it's really anything that the computer can manipulate

      I rewrote this section a bit. Have another read and let me know if it's more clear.

  • Miley

    Hi, I'm still a little confused on this objects subject.

    It is said that -
    "A single piece of data, stored in memory somewhere, is called a value."
    "An object is a region of storage."
    "we can just create objects, give them values, use those objects as we please"

    What do you mean by create objects? the meaning of object is a region of storage therefore, are we aiming to create a region of storage? If so, how do we create a region of storage.

    And when it says "give them values", are we just creating an object and giving it data? as that is what value means.

    • Alex

      An object isn't _just_ a region of storage, it also has other properties such as size, lifetime, a type, etc...

      Objects are "created" when we run our code and those objects become instantiated. The compiler takes care of mapping an object to somewhere in memory. We tell the compiler, "I want an integer object" and the compiler goes, "Okay, I'll put it in memory here" -- we don't have to care about where. Then we can just use the object to store and retrieve values without having to worry about how or where that maps to memory.

      And yes, "give them values" means giving an object a value to be stored in the region of memory that object is associated with.

      • Miley

        When you say "I want an (integer object)" is that defining the object or giving it value?
        If none, what do you do to define an object and what do you need to do to give it value?

        • Alex

          Defining the object. Giving it a value is a separate (and optional) operation.
          You can give an object a value via initialization (preferred) or assignment.

  • Nyther

    Is it okay if I initialize a variable with no value if I am gonna define it right away?
    Example:

    • Well how do you know that @std::cin.operator>> doesn't try reading from the variable and that it overrides it no matter what?
      If you're using C++11 or later, what I questioned is true, but you should always check first. If in doubt, or lazy, initialize everything.

  • John

    "In our programs, most of the objects we create in our programs will be variables."

    Probably better written as: In our programs, most of the objects we create will be variables.

  • 5n1p3r_4rt3m1s

    why does the hash/sharp symbol looking like not-equals to symbol in the page?

  • Anonymous

    Under the objects and variables section I found a typo in the third paragraph, and the second sentence, you say "A object"

  • Mario

    Hi, quick questions regarding quiz answer #2. I was expecting the answer to be 5, being the value assigned to x at initialization. Does this mean that the value of an assignement will superceed the initialization value? and is that always the case, or it will be dicated by the latest r-value?

    • A variable can hold only one value at once. If it gets overridden, the old value is lost.

    • Phil

      Initialization provides the initial value to the variable. But variables can vary over time. The second line assigns a new value to x. The original value is no longer in memory. Therefore, when printing the value of a variable, you will see the value that was last assigned to that variable.

  • Benur21

    Summarizing:

    Definition:

    Assignment:

    Initialization = Definition + Assignment:

    Uninitialized means the Initialization is not complete - you did not do the Assignment of a value to it.

    First you Define, second you Assign and Initalization is complete.

    (correct me if I'm wrong)

    • > Definition
      Correct

      > Assignment
      Correct

      > Initialization = Definition + Assignment
      Only correct for copy initialization, which should be avoided.

      Direct Initialization = Definition + Expression list

      Uniform Initialization = Definition + Braced Init List

  • Kenneth Rios

    I'm compiling using VS 2017. For each of the example programs written in these lessons, would I have to create a new project to run them if I don't want to overwrite the old example program? I'm trying to create separate source .cpp files inside my HelloWorld project which each contain an example code (so each file has its own main() function), but it's spitting out errors. I understand the errors, but is there a way to store these programs instead of making one giant main() function?

    Hopefully my question makes sense...

    • Kenneth Rios

      After some struggle, I figured out that regular code (such as the code in this lesson's Quiz) has to be wrapped inside a function (such as main()) or else it raises an error. That wasn't immediately obvious to me but I was probably being careless.

      Skipping to Lesson 1.8 on working with multiple files helped me, I think. I now understand that I have to declare functions, which are written in other files, inside the main.cpp file and then call those functions within main(). So I got what I wanted to do to work, but I don't know if it's the best way of approaching it. Am I on the right track with this?

  • Joshua G

    For question 1, I assumed that the program would output either 3 or 5 (3 obviously being the correct answer). I just was not sure which "x" the std::cout << x << std::endl; was referring to. Is this a common mistake for beginners? Could a different assignment to "x - 2", such as "a", be used to eliminate such confusion?

    • Hi Joshua!

      There is only 1 @x. In line 1 it's value is 5. In line 2 it's value is overridden with 3 (because 5 - 2 = 3), the 5 is lost.
      Only could store the new value in a separate variable like so

      After this line, @a would be 3 and @x is still 5.

  • Samie

    hey when I put the quiz questions into the my visual studios i got alot of errors saying "this declaration has no storage class" idk what to do so help plz.

  • erk

    hey alex i think you have made mistake in typing the link it go to section .9 but name is
    section .6

  • David McHutchison

    I'm feeling dumb, but I'll ask anyway :o)

    I'm using Visual Studio Community 2017 (v 15.8.8, d/loaded and installed a day or two ago) but when I uncomment the line #include "stdafx.h" as suggested for VS, I get a compile error, "Cannot open include file: 'stdafx.h': No such file or directory". If I leave that line commented out, I get the compilation error "error C4700: uninitialised local variable 'x' used".

    My old coding brain keeps whispering, "Never assume anything!" so I'm reluctant to assume it's okay to do the opposite of what's suggested. Also, I'm not managing to get a clean compile that will let me run the code and see what happens when the variable is uninitiated.

    So, any idea if I've perhaps not set up something correctly, or could it be this latest version of VS has somehow negated the need to code that #include ? (As you can see, I don't fully understand why that line is needed for VS but not for other IDEs.)

    Hoping I don't sound as dumb as I feel!

    • David

      I'm as sure as I can be that I followed the instruction when setting up VS and UNCHECKED the precompiled header option. When I look at the properties for my project, under "Precompiled Headers" it shows:

      Precompiled Header              (blank)
      Precompiled Header File         stdafx.h
      Precompiled Header Output File  $(IntDir)$(TargetName).pch

      Is this correct?

      • Alex

        Sorry for the confusion. These lessons originally recommended Visual Studio users use precompiled headers (since they're on by default), so the lessons in this chapter remind users they need stdafx.h under the presumption that precompiled headers will be on.

        The Microsoft went and changed the name of stdafx.h to pch.h, and I updated the lessons in chapter 0 to recommend turning off precompiled headers. So now these examples are slightly out of date, as I haven't deployed the updated lessons for this chapter yet.

        TLDR: Ignore the comment, as it's only needed if precompiled headers are turned on, and you should now be creating your VS projects with precompiled headers off.

        • David

          No problem Alex, I can imagine how difficult it must be to keep everything up to date. I'm just happy I asked a relatively sensible question! At the moment everything feels "new and different". I'm sure as I gain experience with both C++ and VS I'll come up with some more challenging questions, LOL

          Thanks for the feedback - much appreciated :o)

      • I don't have VS, but according to pictures there should be an option "Not using precompiled headers" for the "Precompiled Header" setting.

        • David

          Yeah, thanks, I noticed that one of the dropdown options for "Precompiled Header" is "Not Using Precompiled Headers" but I was reluctant to change from the current "blank" as I wasn't sure I could put it back to that. ("blank" apparently is not an option in the drop-down list.) I'll have a play around with it at some point. I can always dump the project and start over if I mess up :o)

  • Sourabh

    Hi AlEX,
    I didn't understand how it's sum is 6.   further in Quiz
    std::cout << x + y << std::endl; // #3

  • rohit

    i am not getting the random values......i am doing this on gedit and running it through terminal

    • Alex

      You may or may not get the different values. That's the nature of undefined behavior. It can be incorrect but consistent.

    • rohit

      i am getting the default values of data types like this .....i don't think that these are the garbage values.

  • vbot

    Hi Alex,

    @ "Note: Some compilers, such as Visual Studio, will initialize the contents of memory when you’re using a debug build configuration. This will not happen when using a release build configuration."

    It seems that MSVC (VS 2017 15.8.5) is initializing the contents of memory even when using a release build.
    I ran the second example several times (different builds / rebuilds) and it always outputs "0".

    Thanks.

  • jimin

    At first i assigned x by 5 and then it gave me 3, but when i replaced 5 by 6 it still gave me answer 3. Can so explain that for me ?
    #include <iostream>
    int main()
    {int x = 5; x = x - 2;std :: cout << x;
        return 0;}

    • Hi Jimin!

      Make sure you compile the program before running it. In most cases the button to compile is a hammer symbol. Some IDEs don't compile the code automatically before running it, except for the first run.

  • ishan

    How to disable compiler extensions for Code blocks?

    • Alex

      You can disable compiler extensions for Code::Blocks via Settings menu->Compiler->Compiler flags tab, then find and check the “-pedantic” option.

  • alok

    Why am I getting a 0 when I have compile and run the following code. I am compiling using `cl /EHsc /W4 Uninitialized.cpp`

    <code>
      #include <iostream>

      int main()
      {
        int x;
        std::cout << x;

        return 0;
    }
    </code>

  • John Mosquera

    Thanks for doing and maintaining this guide - I did some testing
    I ran the uninitialized variables programme using Code::Blocks
    std::cout printed the value 4354190 with an execution time :0.292 s (I wonder if my computer is slow)
    A few minutes later I ran it again and printed the same number but faster 0.047 s
    Running it more times with the same printed value and same speed of 0.047 s
    But if I add a blank space to the code and press the build button and run it prints the same number but slower 0.281 s
    Further executions are again 0.047 s
    I now I press build (without adding blank spaces), press build and run with 0.043 s (faster than the norm)
    and run again, it goes to the same 0.047 s
    By removing // comments and some white space, build and run, it went down to 0.031 s (the fastest)
    running again it goes to the same 0.047 s and value remained the same as 4354190 (I may try again at a later date to see if it changes).
    Oops, apologies for my long comments, I got too carried away and went OTT. Thanks

    • Alex

      I'm guessing it has to do with caching -- the first execution of a new program requires loading the program into memory, whereas for subsequent executions it may already be in memory.

  • Haitam

    Wow people still comment here ?

    • Kyle

      reason why is likely people are finding out relying only on apps suck and want to program their own stuff as the "software" industry is shell of it's former self and thinks all you want are apps you rent...  

      Only games are being done on 2,000$ PC's and most are console ports usually crappy reading funny reviews on Steam.  Walk into any store in 2005 and there were GOBS of software of all sorts not just violent games or even games at all!  now you search for software for windows 10 all you get is basic OS maintenance stuff.  same at Office depot boooooooooooooring.

      those who grew up on this tried to gert some of it working thru virtual machines but thet are developed for businesses only like running old server stuff using a Pentium 1  NOT consumer products if it works it's more down to luck then design.

  • Hi Alex!

    "On Visual Studio, you can do this setting is found in"
    I think that should be
    "In Visual Studio, this setting is found in".

  • Nguyen

    Hi,

    Could you please let me know why line 10 gives me an error?

    Thanks

  • Jan Williams

    I got the answers to the quiz correct from reading through them but when I decided it might be fun and good practice to try and put them in Visual Studio I only got the first one to work.  Can you give me a screen shot of what the second one would look like in Visual Studio so I can see what I'm doing wrong? Maybe I can get 3 to work.  (I'm not going to enter 5 or 6).

  • Adrian

    I tried the snippet code for printing the uninitialized integer variable. when I tried the function with an int argument visual C++ gives me error but when I changed it to &argument it's worked fine!
    I know that & operator pass location of variable to function but I don't get it what's happened here.

    // #include "stdafx.h" // Uncomment if Visual Studio user
    #include <iostream>

    void doNothing(int x)    //instead of const int &x I used int x and the file failed to compile
    {
    }

    int main()
    {
        // define an integer variable named x
        int x; // this variable is uninitialized

        doNothing(x); // make compiler think we're using this variable

        // print the value of x to the screen (dangerous, because x is uninitialized)
        std::cout << x;

        return 0;
    }

    • Alex

      When the function parameter is int x, this is a pass by value, so the argument (main's x) is _copied_ into doNothing's x. Therefore the argument isn't changed by the function, and smart compilers will detect this and show an error about using an undefined variable.

      When the function parameter is int &x, this is a pass by reference (covered in a later chapter). In this case, doNothing's x is an alias to the x that main is passing as an argument, so anything doNothing does to x affects the argument. Even though doNothing() doesn't change the argument, most compilers aren't smart enough to realize this, so they disable the error because they can't definitively conclude that x hasn't been assigned a value somewhere along the way.

  • Izak

    Typo: "an known value."
    I think it should be "a known value."

  • Jack

    Am I Right? Short Recap.

    an integer (int) is a number that can be written without a fractional component such as -12 0 or 109.

    an integer works this way.

    int x; //you gotta tell the compiler its an integer before assigning a value to the integer.
    x = 5; // this is the value ive chosen to give my integer

    cout << x <<endl; //notice that i didnt put colons? Thats because your printing a value of another variable otherwise it would say x!

    • nascardriver

      Hi Jack!

      > an integer (int) is a number that can be written without a fractional component such as -12 0 or 109.
      Correct

      Prefer initialization over assignment. If you can't initialize a variable to the correct value initialize it to 0 or equivalent.

      > notice that i didnt put colons?
      This is a colon :, if mean an single quotation mark you're right.

  • Everything is going smoothly so far.
    You guys did a great job by putting up a quiz at the end!
    It definitely makes it feel like I'm doing this at school. I've been hooked for hours, I'm not sure if I'll be able to sleep, haha:-D.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]