Search

1.3 — A first look at variables, initialization, and assignment

Objects

C++ programs create, access, manipulate, and destroy objects. An object is a piece of memory that can be used to store values. You can think of an object as a mailbox, or a cubbyhole, where we can store and retrieve information. All computers have memory, called RAM (random access memory), that is available for programs to use. When an object is defined, a piece of that memory is set aside for the object.

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

Variables

A statement such as x = 5; seems obvious enough. As you might guess, we are assigning the value of 5 to x. But what exactly is x? x is a variable.

A variable in C++ is simply an object that has a name.

In this section, we are only going to consider integer variables. An integer is a number that can be written without a fractional component, such as -12, -1, 0, 4, or 27. An integer variable is a variable that holds an integer value.

In order to create a variable, we generally use a special kind of declaration statement called a definition (we’ll explain the precise difference between a declaration and a definition later). Here’s an example of defining variable x as an integer variable (one that can hold integer values):

When this statement is executed by the CPU, a piece of memory from RAM will be set aside (called instantiation). For the sake of example, let’s say that the variable x is assigned memory location 140. Whenever the program sees the variable x in an expression or statement, it knows that it should look in memory location 140 to get the value.

One of the most common operations done with variables is assignment. To do this, we use the assignment operator, more commonly known as the = symbol. For example:

When the CPU executes this statement, it translates this to “put the value of 5 in memory location 140”.

Later in our program, we could print that value to the screen using std::cout:

l-values and r-values

In C++, variables are a type of l-value (pronounced ell-value). An l-value is a value that has a persistent address (in memory). Since all variables have addresses, all variables are l-values. The name l-value came about because l-values are the only values that can be on the left side of an assignment statement. When we do an assignment, the left hand side of the assignment operator must be an l-value. Consequently, a statement like 5 = 6; will cause a compile error, because 5 is not an l-value. The value of 5 has no memory, and thus nothing can be assigned to it. 5 means 5, and its value can not be reassigned. When an l-value has a value assigned to it, the current value at that memory address is overwritten.

The opposite of l-values are r-values (pronounced arr-values). An r-value refers to values that are not associated with a persistent memory address. Examples of r-values are single numbers (such as 5, which evaluates to 5) and expressions (such as 2 + x, which evaluates to the value of variable x plus 2). r-values are generally temporary in nature and are discarded at the end of the statement in which they occur.

Here is an example of some assignment statements, showing how the r-values evaluate:

Let’s take a closer look at the last assignment statement above, since it causes the most confusion.

In this statement, the variable x is being used in two different contexts. On the left side of the assignment operator, “x” is being used as an l-value (variable with an address) in which to store a value. On the right side of the assignment operator, x is evaluated to produce a value (in this case, 7). When C++ evaluates the above statement, it evaluates as:

Which makes it obvious that C++ will assign the value 8 back into variable x.

For the time being, you don’t need to worry about l-values or r-values much, but we’ll return to them later when we start discussing some more advanced topics.

The key takeaway here is that on the left side of the assignment, you must have something that represents a memory address (such as a variable). Everything on the right side of the assignment will be evaluated to produce a value.

Initialization vs. assignment

C++ supports two related concepts that new programmers often get mixed up: assignment and initialization.

After a variable is defined, a value may be assigned to it via the assignment operator (the = sign):

C++ will let you both define a variable AND give it an initial value in the same step. This is called initialization.

A variable can only be initialized when it is defined.

Although these two concepts are similar in nature, and can often be used to achieve similar ends, we’ll see cases in future lessons where some types of variables require an initialization value, or disallow assignment. For these reasons, it’s useful to make the distinction now.

Rule: When giving variables an initial value, favor initialization over assignment.

Uninitialized variables

Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location! A variable that has not been given a known value (through initialization or assignment) is called an uninitialized variable.

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.

Using the values of uninitialized variables can lead to unexpected results. Consider the following short program:

In this case, the computer will assign some unused memory to x. It will then send the value residing in that memory location to std::cout, which will print the value. But what value will it print? The answer is “who knows!”, and the answer may change every time you run the program. When the author ran this program with the Visual Studio 2013 compiler, std::cout printed the value 7177728 one time, and 5277592 the next.

If you want to run this program yourself, make sure you’re using a release build configuration (see section 0.6a -- Build configurations for information on how to do that). Otherwise the above program may print whatever value your compiler is initializing memory with (Visual Studio uses -858993460).

If your compiler won’t let you run this program because it flags variable x as an uninitialized variable, here is a possible solution to get around this issue:

Using uninitialized variables is one of the most common mistakes that novice programmers make, and unfortunately, it can also be one of the most challenging to debug (because the program may run fine anyway if the uninitialized value happened to get assigned to a spot of memory that had a reasonable value in it, like 0).

Fortunately, most modern compilers will print warnings at compile-time if they can detect a variable that is used without being initialized. For example, compiling the above program on Visual Studio 2005 express produced the following warning:

c:vc2005projectstesttesttest.cpp(11) : warning C4700: uninitialized local variable 'x' used

A good rule of thumb is to initialize your variables. This ensures that your variable will always have a consistent value, making it easier to debug if something goes wrong somewhere else.

Rule: Make sure all of your variables have known values (either through initialization or assignment).

Undefined behavior

Using the value from an uninitialized variable is our first example of undefined behavior. Undefined behavior is the result of executing code whose behavior is not well defined by the language. In this case, the C++ language doesn’t have any rules determining what happens if you use value of a variable that has not been given an known value. Consequently, if you actually do this, undefined behavior will result.

Code implementing undefined behavior may exhibit any of the following symptoms:

  • Your program produces an consistently incorrect result.
  • Your program produces different results every time it is executed.
  • Your program behaves inconsistently.
  • Your program seems like its working but produces incorrect results later in the program.
  • Your program crashes, either immediately or later.
  • Your program works on some compilers but not others.
  • Your program works until you change some other unrelated code.

Or, your code may actually produce the correct behavior anyway. The nature of undefined behavior is that you never quite know what you’re going to get, whether you’ll get it every time, and whether it’ll change when you make other changes.

C++ contains many cases that can result in undefined behavior if you’re not careful. We’ll ensure we point these out in future lessons. Take note of where these cases are and make sure you avoid them.

Rule: Take care to avoid situations that result in undefined behavior.

Quiz
What values does this program print?

6) What is undefined behavior?

Quiz Answers

To see these answers, select the area below with your mouse.

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

6) Show Solution

.

1.3a -- A first look at cout, cin, and endl
Index
1.2 -- Comments

251 comments to 1.3 — A first look at variables, initialization, and assignment

  • Darius

    Howdy folks, what am i doing wrong, i don’t seem able to add line breaks!!

  • daniel

    another question sir,
    Quiz:
    Solution 3.

    question…it evaluates to 6? but previous statement we declared int y = x; so y was also representing x? or y was representing actual value 3?

    OR
    we declared x and y both for value 3? so if we have to address or represent 3 we can use x or we can use y?

  • daniel

    well new to coding/programming stuff, call me a nub but i am having confusion this:

    int x;

    we use, this "int" what does it stands for? integer or initialize?

  • Rohit

    It showed errors:

    error: ‘endl’ was not declared in this scope|

    So i used std::endl and it worked. But "z" was printing "0" everytime.

    • Alex

      z hasn’t been assigned a value. So it’ll print whatever happens to be in the memory location that is assigned to z. In many cases, that will be 0, but it could be anything.

      • Rohit

        Are you sure same is the case with C++11? Maybe they have now changed this! Now it may assign default value "0".

        • Alex

          Yes, I’m sure.

          If you run your program in a debug build configuration, the compiler may initialize your variables to 0 for you. It won’t do this in a release configuration.

  • Rohit

    "In C++, variables are a type of l-value (pronounced ell-values)." - pronounced ell-value(no "s").

  • Kerberos

    I created a Win32 console application. Was I supposed to create a Win32 project instead?

    When I started the program without debugging, the cmd.exe window displayed it as an .exe  file.

    When I start the program:

    "c: […].exe" is not recognized as an internal or external command, operable program or batch file.

    Is the startup path same as a network path or location address?

  • Kerberos

    Hi. I have a problem understanding this error:
    ‘Program is not recognized as an internal or external command, operable program or batch file (9009)’

    This pops up when I try to start my program for these little quizzes.

    Thanks in advance.

    • Alex

      It sounds like Visual Studio can’t find your executable, however there are lots of reasons that could happen.

      A few things to check:
      1) Did you create a Win32 console project?
      2) When you compiled your program, did it actually create an .exe file? (If it created a .dll instead, you created the wrong type of project).
      3) Open your project properties and make sure that your startup path is correct.

  • Pofke1

    Im using visual studio 2015 and it seems to not make random variables when theyre not set. So when i use

    it says:
    error C4700: uninitialized local variable ‘x’ used
    but when i add x=5; etc it prints 5..
    just saying.

  • King Ron

    I tried this but I never got a result even after switching it to the release configuration

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

    void doNothing(const int &x)
    {
    }

    int main()

    {
        //declare an integer variable named x
        int x;

        //trick the compiler into thinking this variable is used
        doNothing(x);

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

            std::cin.clear();
            std::cin.ignore(255, &apos;\n&apos;);
            std::cin.get();

            
    }

  • Brian

    Wow, great tutorial on variables! I have worked with C++ before but was totally unaware that uninitialized variables could slip past the compiler.

  • gigi

    Can you add return 0 in your example?

  • chirag

    // HelloWorld.cpp : Defines the entry point for the console application.
    //

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

    int main()
    {
        int x = 5;
        x= x-2;
        std::cout<<x<<std::endl;
        int y=x;
        std::cout<<y<<std::endl;
        std::cout<<x+y<<std::endl;
        std::cout<<x*y<<std::endl;
        int z=x+y;
        std::cout<<z<<std::endl;
        int a=x+y*z;
            std::cout<<a<<std::endl;
        return 0;
    }
    the answer is 21 why y*z was multiplied first than x was added

    • Alex

      This is how mathematics works in real life. Multiplication and division before addition and subtraction.

      There’s an acronym that makes it easy to remember the order of math: PEDMAS. Parenthesis, exponent, division, multiplication, addition, subtraction.

  • newprogrammer

    Is it possible to declare a variable in the middle of a statement(like below…declaring x as int then passing it to cout) or does the declaration statement always need to be on its own statement line?
    thanks

    • Alex

      Your line of code is actually an expression, and variables can’t be declared as part of an expression.

      Variables must be declared in a statement.

  • Hobbiest

    Maybe a better question is where did stdafx.h com from. Or where do any of the #include programs (functions?)come from?I did not create it, I did not load it yet the program needs it to run.

    By the way on this example I commented it out and it runs fine.

    Again, thanks for helping me understand this.

    • Alex

      .h files typically come from one of two places: libraries (like the standard library) or files that you create yourself as part of your program.

      However, stdafx.h is something that Visual Studio uses when precompiled headers are turned on. If you’re not using Visual Studio, you don’t need it. And if you are, you can just leave it blank for now. You won’t need to worry about it until your programs get large.

  • hobbiest

    I am trying to run the program from the lesson above (uninitialized variable) but am receiving an error from the line:
    #include "stdafx.h"

    the compiler cannot find stdafx.h

    The actual error message is
    Error    1    error C1083: Cannot open include file: ‘stdafx.h’: No such file or directory    c:\users\pc\documents\visual studio 2013\projects\project1\project1\source.cpp    1    1    Project1

    I am using MS Visual Studio (2013)

    Any suggestions?

    Thanks \!

    • Alex

      There are a lot of reasons this could happen. I’d paste the error into Google and see if any of the articles that come up help you resolve this.

  • Odgarig

    Hello, I’m really thankful to you for letting us learn C++.I was doing fine so far till end of this section.And I have a question.In Quiz 1 we define x as 5 (is a r-value=>I just keeping myself remember it) and x=x-2. And we’re printing x on a console. And what I thought was it would be a wrong code because x assigned to 5 which means the last defined variable equals to 5=5-3 which means can’t be true.And when I checked the answer, it’s output was 3.An another question is the code written in the quiz section wouldn’t have a { at the beginning of the code (I mean after main() function) and } at the end of the code ? .I would be very happy with your answer AND THANK YOU.

    • Alex

      Good question. In the statement:

      x is being used in two different contexts. On the left side, x is being used as an l-value (variable). On the right side, x is being used as an r-value, and is being evaluated only for its value.

      So C++ isn’t evaluating this as “5 = 5 - 2”, it’s evaluating it as “x = 5 - 2”, which makes a lot more sense. I’ll try to clarify this in the lesson itself.

  • Tito

    Perhaps you should also introduce character variables in this section as well? When I got towards the end of the chapter with the calculator it would have been helpful. Someone posted a pretty good example in the comments, and it was simple enough after I knew "char".

    • Alex

      I agree it would be helpful in some cases, but for this chapter, simplicity is the key. Adding char introduces some complexity for not much gain at this point.

  • Twisted Code

    Is it acceptable to take advantage of the ability to use an uninitialized value and use it for a pseudorandom function?

    • Alex

      This isn’t a good idea. The behavior of uninitialized variables is undefined, so you can’t assume anything about them, including whether they’ll be suitably unpredictable!

      If you want a pseudorandom generator, use a well established one, like Mersenne Twister. See section 5.9 -- Random number generation for more information about this.

      • Twisted Code

        Yeah, I kind of figured that the undefined nature would be an inherent problem, but I figured I’d throw it out there. Might even be worth including as a little note in the body of the lesson? idk

  • Chris

    The comments in the code for this lesson… aren't they "bad"? Seems to me you commented against how you advised to comment in the previous lesson. Furthermore the //comments that take up 2 lines do not turn green in visual studio. What gives???

    Also the code:

    When I ran the above code just as is in Visual Studio uncommenting the part I needed to it ran correctly but the cmd window instantly shut down, not giving me enough time to see the output. I had to modify it as follows:

    But. . . . I didn't have to modify the Hello World code to make my output box stay open long enough to view it. Could you tell me why?

    • Alex

      Yes, the comments I use throughout the code examples are horrible by normal standards! But that’s because my goal here is to teach you how things work, and comments are an integral part of that process.

      No idea why the console for one of your programs stayed open and the other didn’t. I’ve never had an issue with visual studio closing my consoles, assuming I’ve executed the program from the IDE. Running the exe directly is another story.

  • Catreece

    Disappointment get.

    Saw the program to spit out whatever number X gets defined to and decided to run it myself out of curiousity. It would seem Visual Studio 2013 has since fixed this issue and will refuse to compile, stating that X is undefined.

    Shame, that. It would've been the first thing I did every time I sat down to learn more programming stuff, just test to see what X is today.

    I wonder if there's any way to get around the error?

    error C4700: uninitialized local variable 'x' used

    It used to work on older versions, so this implies that something about the source code of the compiler changed to look for that issue, which's a good thing, mostly. It also implies that it may therefore be possible to flat out tell it to run that line and ignore whatever errors it gets.

    …Actually, now I'm also curious if it's GOOD or BAD that I'm actively trying to think of ways to break the compiler for my own entertainment… Probably bad. Oh well.

    • Alex

      Try this:

      When I ran this on VS2013 (release configuration), I got 7177728.

      • Catreece

        Huh, interesting. Maybe I just randomly got an unreadable chunk of memory and it got pissy about a non-interger value? Great, now I need to test this again. =P

        Yep, looks like that was it. Testing aaaand… -858993460

        Thanks, I could've gone my life without knowing this. Bloody enabler! XD

        Seriously though, thank you, I guess I just got unlucky the first time =3

      • James

        I was interested to know more about void:

        https://msdn.microsoft.com/en-us/library/yah0tteb.aspx

        I ran this code:

        I found out that in order to display code and any symbols correctly, you have to copy and paste the code from the IDE into a new comment with code tags. Editing any comment will cause symbols to display incorrectly, e.g. & displays as &amp.

        Also, if you run the code without debugging with output set to display in debug, the console will pop up momentarily and the output will show in the debug output in the IDE.  The output has to be set to build and the build configuration set to release.

    • macks2008

      What is bad about having fun trying to understand what's going on (by "breaking" the compiler)? Isn't that the entire *point*  of learning a programming language? If you think it's bad to have fun circumventing restrictions placed on oneself by programmers (of the IDE), I think you might be on the wrong boat. Take chances, make mistakes, get messy! (Great, now I'm quoting children's shows)

  • Paul

    Initialising a (real) variable with -1 is in my opinion not the best practice.
    For performance one may choose a unsigned datatype and -1 will not work with this? So you will have to switch to signed just to be able to tell if it’s declared?

    Any better options? Probably declaring with a standard value or 0?

  • Ethanicus

    Hey, Alex.

    I noticed that you said
    std::cout << cats << "cats"
    and it printed “-1 cats”.

    How would you change a variable to be text? For instance,
    int name = "Joe"
    std::cout << "Hello, " << name << std::endl;
    so it will say "Hello, Joe."
    I can't seem to get it to work.

    • Alex

      That’s because you’ve declared name as an integer (number), not a string (sequence of letters). I talk more about strings in section 6.6 -- C-style strings and an introduction to std::string.

      Unfortunately, in C++, strings are more complicated than they should be.

    • Darren

      Use a pointer to a character type e.g.

      which is equivalent to

      Alternatively (and I recommend this because char* are a pain in the bum) use the string class defined in the standard header e.g.

  • Landru598

    Thank you for these tutorials, they are straight forward and include what you have to know. By the time I finish all of these sections should I be able to program games like pingpong?

  • ballooneh

    “One common trick that experienced programmers use is to assign the variable an initial value that is outside the range of meaningful values for that variable. For example, if we had a variable to store the number of cats the old lady down the street has, we might do the following:

    1
    int cats = -1;
    Having -1 cats makes no sense. So if later, we did this:

    1
    cout << cats << " cats" << endl;
    and it printed “-1 cats”, we know that the variable was never assigned a real value correctly."

    Could anyone help explain this to me? I seriously need help on this. Talk to me… like a 10 year old if you can 😀

    • Alex

      Imaging you’re writing a program where you’re keeping track of how many cats are being adopted out today.

      You run the program, and it prints, “We adopted out 0 cats today!”. Is this correct, or have you made an error somewhere and done a calculation wrong? It’s not clear.

      Now consider this program:

      If the code prints, “We adopted out 0 cats today!”, you know you really didn’t adopt out any cats.
      If the code prints, “We adopted out -1 cats today!”, you know there’s a problem in your program somewhere, because nCats should have never been left with the value of -1.

  • AIKS

    why is main() function preceded by int ? my reference books show the use of void. does it make any difference?

  • Homesweetrichard


    #include

    int variables ()
    {
    using namespace std;

    cout <> b;

    int e;
    e = b*10;

    int l;
    l = e/100;

    int a;
    a = e+b;

    int d;
    d = l+e;

    int s;
    s = 2*(d-a);

    int m;
    m = b+l;

    cout << b << e << l << a << d << s << m;

    return 0;

    }

    • mukulgarg_jec

      you are missing main() function. Updated code is

      #include “stdafx.h”
      #include
      int main()
      {
      using namespace std;

      cout <> b;

      int e;
      e = b*10;

      int l;
      l = e/100;

      int a;
      a = e+b;

      int d;
      d = l+e;

      int s;
      s = 2*(d-a);

      int m;
      m = b+l;

      cout << b << e << l << a << d << s << m;

      return 0;

      }

  • marki123

    when i compiled the program that uses the cin cout. i enter the number then press enter and suddenly the program closes. and this is the code i compiled.please tell me if there is anything wrong with it. (im using code blocks but on windows)

    #include

    int main()
    {
    using namespace std;
    cout<>x;
    cout<< "You Entered"<< x <<endl;
    return 0;
    }

    • That’s because there’s nothing that prevents the program from closing after the cout runs. IIRC Code::Blocks had a bug which would sometimes bug out the thing that’s responsible for keeping the window up once the code has been executed (cin related too, I think).
      Just put a cin.ignore().get(); after the cout line.

  • ahoora

    I am so glad to find your website. There is a very logical rationale behind your explanation which makes it simpler and at the same time joyful to learn.

    Many thanks for all the hard and smart work.

  • see-going

    Q: why does declaring a variable using
    int (A);
    work the same as
    int A;

    ??? should there be a difference between the two declaration statements, esp given that the variable name is enclosed in brackets?

    • I don’t think that there’s a difference, no. Still, enclosing a variable name in brackets looks kind of silly and is redundant.

    • Alex

      *answer removed to avoid confusion, see below*

      • Abilasha

        #include <iostream>
        int main()
        {
        int (a)=10;
        std::cout << a << std::endl;

            return 0;
        }

        output: 10 its working fine.

        • Alex

          Yup, it looks like C++ allows you to define your variable names inside parenthesis. There’s probably a specific reason for this (e.g. to keep consistency with the way pointers to functions are defined).

          However, just because c++ allows you to do something doesn’t mean you should, and defining your variables this way violates best practice.

  • Yahsharahla

    Hi after several attempts of my program not running after question # 1 on the quiz I finally got it to run by using:

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

    int main()
    {
    using namespace std;
    int x = 5;
    x = x - 2;
    cout << x << endl; //#1
    cin.clear ();
    cin.ignore(255, '\n');
    cin.get ();
    int y = x;
    cout << y << endl; //#2
    cin.clear ();
    cin.ignore(255, '\n');
    cin.get ();
    cout << x + y << endl; //#3
    cin.clear ();
    cin.ignore(255, '\n');
    cin.get ();
    cout << x << endl; //#4
    cin.clear ();
    cin.ignore(255, '\n');
    cin.get ();
    int z;
    cout << z << endl; //#5
    cin.clear ();
    cin.ignore(255, '\n');
    cin.get ();
    return 0;

    }

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter