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

367 comments to 1.3 — Introduction to variables

  • Anderson

    Hello, I just read this article and I'm a bit confused now:
    http://en.cppreference.com/w/cpp/language/zero_initialization
    On C++ 14, variables are automatically initialized to 0?

    • Alex

      Not usually. However, it's hard to determine what initialization rules apply to what cases, as C++'s initialization rules are a _mess_.

      In some cases, variables will be zero initialized. Common examples include classes where no constructors have been provided, and arrays where there are some initializers but not enough to initialize all the elements.

      In general, it's better to just assume variables won't be initialized, and always provide an initializer or constructor to do the initialization.

  • gSymer

    Hey Alex!
    I am currently also learning Python, and notice that Python easily handles integers of any length, whereas in c++, when I wrote a program that takes an integer input from the user and prints its double, the program would give useless answers like -2, -89990 etc, for inputs larger than about 10 digits. Why is this so, and how to get around this problem, so that I can input numbers of arbitrarily length and get the correct answer, just like in Python?

    • nascardriver

      Hi gSymer!

      > Why is this so
      You're getting weird results, because either you're overflowing the number or converting the int to a double in a wrong way.

      > how to get around this problem
      The most universal number is a long double. If you want numbers like they are in python you'll have to write your own class that handles numbers of arbitrary size.

  • Luis Melo

    Hello,

    I would like to know if instantiation refers to the process of assigning a portion of memory to especifically int variables, to variables in general or to all sorts of objects.

    Thank you for the attention

  • Mikey

    im useing Xcode on Mac

    when i put in the code i am having a red error message pop up telling me i have "conflicting types for 'main'

    how do i trace back to this mistake.

    I'm really enjoying these lessons, I'm just starting out and everything thus far has been presented in comprehensive manor. and im glad to see that some of the comments are recent.

    thank you

    • nascardriver

      Hi Mikey!
      I don't know anything about Xcode, you'll have to search for a solution on your own or wait for someone who knows.
      Up until then you can use an online IDE like https://www.onlinegdb.com/ (Select C++14 as language, top right).

  • Kieran Doherty

    I am having issues with the code as it is bringing up x as undefined or is this done on purpose?

    #include "stdafx.h"
    #include <iostream>

    void doNothing(const int &x)
    {

    }

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

        doNothing(x);

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

        return 0;
    }

    • Alex

      x definitely isn't undefined -- it's defined at the top of main.

      Can you post the actual error message you're seeing, along with the specific line it's referring to?

  • Tyler S.

    Hey Alex, I believe I’ve found a minor typo in the section for l-values and r-values.

    When explaining r-values, line 6 of the first example reads:

    "x = y;      // l-value y evaluates to 7 (from before), which is then assigned to l-value x."

    I believe the beginning of the comment should read "r-value y evaluates to 7 (from before)" and not "l-value y evaluates to 7 (from before)".

    Sorry if I’m mistaken! I do realize that y had been assigned as a l-value in the past but with it being used on the right side of the assignment, would that have made it a r-value for that line?

    Thank you for all the work that you do. I really, really appreciate it!

  • Morteza

    somewhere in the text you have said: (the = sign);
    i think this will rise misunderstanding. i suggest to fix is as: ("=" sign)

  • dolx

    Thank you for this. Been coding for a few months but I stopped doing some tutorials and now when doing some projects I feel like there's a gap in my knowledge, therefore I've come here. This is real helpful, thank you.

  • Karen

    Hi, Alex.

    I was able to run the Hello World program in chapter 0.6. I was also able to run it using the sample code (just commented out the previous lines) of not initializing. However, after initializing it, I encountered an error. I reverted it to the Hello World code, it produces the same error:

              === Build: Debug in HelloWorld (compiler: GNU GCC Compiler)...
    ld.exe    cannot open output file bin\Debug\HelloWorld.exe Permission...
              error: ld returned 1 exit status
              === Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 ...

    What could be the problem?
    Thank you! :)

    • Alex

      It sounds like you've lost permission to overwrite HelloWorld.exe. The most obvious way this would happen is if HelloWorld.exe is still running. Make sure the program has closed (if you can't figure out how, try rebooting). Other possibilities would be virus scanners or anti-malware interfering with writing the file.

  • Thirteen Spades

    Hi Alex;

    I put the following code into Visual Studio 2017, and it came up saying, -> C2143   syntax error: missing ';' before 'return'
    Also, how do I do the cool code thing you do in the comments with the colors?

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

    void doNothing(const int &x)
    {
    }

    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;
    }

  • Hema

    I am looking for a data type which accepts fraction as the input and then convert it into a decimal. Is there any?

    • Alex

      You can use a float or a double and do something like this:

      • Hema

        I will not be initialising the variable. The value will be given by the user during the run-time. Will double work in this case too?

        Thanks

        • Alex

          Kinda sorta not really. :)

          A double will store the decimal value, but it won't convert a user-entered fraction into a decimal. To do that, you'll need to write your own code.

          The initialization method works because the compiler will treat 5/3 as 5 divided by 3, which it will resolve to 1.66666... But it can only do that at compile time.

          • Hema

            1) Could you give a hint for writing the code to  convert a user-entered fraction into a decimal.

            2) I wrote the code in gedit and compiled it in Ubuntu terminal which supports c++11. It prints 1. How can I solve this problem?

            3) Do you get annoyed answering so many question everyday!?

            Thanks

            • Alex

              1) I'd recommend writing a class for this. Lesson 9.3 contains a sample Fraction class that could do this.
              2) Your code is doing integer division. You'd need to do something like this:

              We cover doubles and the difference between integer and floating point division in chapter 2.
              3) Sometimes. :) But mostly for questions that have already been answered a thousand times. And for the remaining questions, mostly because answering questions takes away time from writing new stuff.

  • Robert Bristow

    Hello,
    I have been doing relatively minor coding in VBA and SQL for a few years now and seriously thinking about taking up C++.  So far these tutorials have been great.  In this section, even though the syntax is different the concept and output are right in line with VBA and mostly understandable to me.  However, I do wonder about possible subtleties.  Specifically, can the variables be more than one character.  X & Y are common variables to anywhere and I understand why you use them in your examples but is it safe to assume that something more descriptive could be used as well?  Say something like strcnt for string count.  Int strcnt = 5, for instance.  Then, for initialization, is zero always an acceptable value?  Are there any instances when a zero would cause an error?  I would not think it would cause any errors but would like to be clear on it as it seems that would logically be the safest practice.  

    Thanks

    • Alex

      Yes, variable names can be multiple characters. Variable naming conventions are covered in a few chapters. Initialization is a valid initialization value for all the fundamental types (like int, char, double, etc...), but may not be valid for user defined types, such as enums, structs, and classes.

  • Aditya

    Hi again Alex!

    I think that you need to mention that variables need to be declared in every function separately. It isn't there and caused a lot of confusion in 1.4a excersise #5.

  • phong nguyen

    I'm using Visual Studio Community Ed. 2017. When I'm in Debug, a warning will pop up, unable to do anything else. When I'm in Release, uninitialized variables are initialized to 0.

    • Alex

      > When I’m in Debug, a warning will pop up, unable to do anything else

      What warning are you getting?

      > When I’m in Release, uninitialized variables are initialized to 0.

      This may be incidentally true, but is not guaranteed.

  • Ali

    I've seen many c++ tutorials
    all of them disappointed me, until I saw yours.
    I love how everything is explained in simple language without skipping stuff or over-complicating anything. Thank you.

  • Machinima Machinima

  • Ayush

    int main()
    {
        int x
        cout << x;
        return 0;
    }

    It gives an "C4700 uninitialized local variable" error in visual stdio 2015.

  • phong nguyen

    int x;
    std::cout << x  + "Abs";
    _______________________________________________
    Running this in **Release**
    output: Abs
    w/o string "Abs", output: 0
    _______________________________________________

    Running this in **Debug**
    output: "Error, variable x is being used without being initialized"
    ________________________________________________
    FYI, I am using visual studio community 2017 edition. I thought it was supposed to be the other way around where I get error in **Relase** and not **Debug**. THank you

    • Alex

      I would have expected you to get the same error in both cases, since that's a compiler error, not a runtime error. Not sure why the behavior is different.

  • Nathan

    Hi,

    I'm running the following code below and it is only returning the value 0. I thought that it would print the memory location or something, I'm super confused. I'm using the release build on Visual Studio.

    Am I doing something wrong or is this just how C++ works now?

    Thanks,
    Nathan.

    • Alex

      It's how C and C++ have always worked. Sending a variable to std::cout prints the value that the variable holds. In this case, since you haven't initialized x, you'll get an undefined value.

      If you want to print the memory location of x for some reason, you can use the & operator to get the address of x:

  • Ben Irwin

    I just noticed an English language error in the form of a missing "the".

    Current: Most of the objects that we use in C++ come in form of variables.

    Should Be: Most of the objects that we use in C++ come in the form of variables.

  • Rrr

    #include <iostream>
    Int main ()
    {
    Int x;
    x=5;
    x=6;
    std::cout<<"x";
    Return 0;
    }
    It will first assign value 5 to x and then overwrite to 6 right???

  • jenifer

    Hey, can u help me answering this.  Which of the following C expressions are l-values? Why?

    1. x +2

    2. &x

    3. *&x

    4. &x + 2

    5. *(&x +2)

    6. &*y

    • Alex

      This sounds like a homework assignment. Rather than answering for you, let me give you a hint: if you can take the address of the result, it's an l-value.

      With that knowledge, you should be able to determine your answers experimentally (i.e. try it).

  • Freddy G

    Awesome tutorial. I'm an old man trying to learn programming and I appreciate you for teaching this old dog new tricks!

  • My dear c++ Teacher,
    Please let me say what I understand,  and what not, regarding "Initialization vs. assignment".
    I understand that C++ will let you both define a variable AND give it an initial value in the SAME STEP. It follows, when a variable is defined and THEN assigned a number, is NOT initialized, is uninitialized. It is defined and assigned (a number) in two steps (statements).
    When it is not assigned a number, either by "assignment" or by "initialization", should be said "unassigned".
    "Uninitialized" is meant not initialized, but may be defined and assigned in two steps.
    With regards and friendship.

    • Alex

      We colloquially use the term "uninitialized" to mean the variable has not been given a value yet (by any means). If the variable is later assigned a value, we say the variable is no longer uninitialized, even though we gave it a value via assignment.

  • Dennis

    Hi,

    class variables of for example std::string can have default initialization, see

    http://en.cppreference.com/w/cpp/language/default_initialization

    I know this will be talked about later in this tutorial. People might get the impression that all variables are not initialized at all. Maybe add a note that this is not always the case.

    • Alex

      I updated this lesson to note that "most" variable don't self-initialize. Although it's certainly true that some types of variable do self-initialize, I don't think that's particularly relevant to know at this point in the tutorial, since we don't cover those types of variables for quite some time. For now, it's better to act as if no variables self-initialize, and then we'll cover those other cases later.

  • My dear c++ Teacher,
    Please let me following comment:
    First two sentences are:
    "C++ programs create, access, manipulate, and destroy objects. An object is a piece of memory that can be used to store values."
    It means c++ programs eventually destroy pieces of memory!
    By the way let me wish you enjoy a Hawaiian pizza and a pint of Newcastle.
    With regards and friendship.

  • Someone confused with C++

    Okay, so I had failures going with the code. It looks like that:

    But it was still giving me two errors:
    C2065: "cout": undeclared identifier
    C2065: "endl": undeclared identifier
    How do I solve it? I've sifted through the comment section, but still no solution.

  • My dear c++ Teacher,
    Please let me say you Visual Studio 2017 behavior when variable "x" is uninitialized.
    A. After pressing "Build Solution":
    1. Seven lines, three of them are Addresses in hard disk. First address is followed by
    "warning C4700: uninitialized local variable 'x' used"
    2. Last line is
    "Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped".
    B. After pressing "Start Without Debugging":
    Console window is appeared just saying (in french) "press any key to continue..."
    With regards and friendship.

    • Alex

      Yes, your compiler is giving you a warning that you are using an uninitialized local variable. This is not an error though, so the compilation succeeds. Your program may not perform as you expect though.

  • My dear c++ Teacher,
    Please let me send you following program for your quiz, with std::endl after every output, so that numbers be on different lines.

    With regards and friendship.

  • Billy Bob Joe

    hi,
      I was wondering how to initialize strings?

    • Alex

      It depends on what kind of string you're referring to. Strings in C++ are a little more complicated than in some other languages. I talk about std::string in chapter 4, and C-style strings in chapter 6.

Leave a Comment

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