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

  • Helleri

    What does the l in l-value and the r in r-value stand for? right and left?

    …also I don’t get how I can go as far as to copy the thing I was supposed to do exactly and there are build errors or something. It seem to do the exact same thing the last program did…

    …what does cout stand for? what does cin stand for? why is << sometimes facing one way and sometimes facing another without an obvious reason?

    • 1) Yes, r-value stands for right value, and l-value stands for left value.
      2) What errors are you talking about? Did you copy only the code without the line numbers? did you remove the VS part?
      It’s quite possible that the author had some typos, but it might be a problem on your end too.
      3) c - standard (don’t ask me), out - output, in - input. As for ‘>>’ and ‘<<' - I can't really explain why is that.

    • cout stands for "Character OUTput", and cin stands for "Character INput"

  • JLaughters

    When I run this program it looks like I input a number and always get output of 0.
    It should take the user input in function input1 and save it to variable a. Then return a to main to be cout. I added a cout in input1 after the user input to see if the user’s inputs was being stored as a. It was. It seems though that when a is returned to main a is being reset to 0.

    • senthil

      you are printing the local copy of ‘a’ and not the return value. The local copy of ‘a’ is initialized to 0 and not changed anywhere in the main. hence 0 is displayed.

      solution:
      update the local copy of ‘a’ with the return value.


      a = input1(a);
      cout << a;

    • rameye

      Or simply pass the variable to input1() by reference instead of by value. Like this:


      #include <iostream>

      void input1(int& a)
      {
      using namespace std;
      cin >> a;
      }
      int main()
      {
      using namespace std;
      int a = 0;
      input1(a);
      cout << a;

      return 0;
      }

    • mymamacalled

      You put in "return 0;", so the program returns 0.

  • lisyhave

    Why doesnt this work?? have tried to change some functions but it is taken from the solution from question 5.

    #include “StdAfx.h”

    #include

    int doubleNumber(int x)
    {
    return 2 * x;
    }

    int main()
    {
    using namespace std;
    int x;
    cin >> x;
    cout << doubleNumber(x) <> x;
    x = doubleNumber(x);
    cout << x <---- Build started: Project: igne, Configuration: Debug Win32 ----
    1> igne.cpp
    1>c:\users\mathias\desktop\projects\igne\igne\igne.cpp(24): error C2084: function ‘int main(void)’ already has a body
    1> c:\users\mathias\desktop\projects\igne\igne\igne.cpp(13) : see previous definition of ‘main’
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Maggie

      The following is my code :

      #include “stdafx.h”
      #include 
      
      int doubleNumber(int x)
      {
      	return 2 * x;
      }
      
      int _tmain(int argc, _TCHAR* argv[])
      {
      	using namespace std;	
      	int x;
      	cin >> x;
      	cout << doubleNumber(x)<<endl;
      	x = doubleNumber(x);
      	cout << x<<endl; 
      	return 0;
      }
      
      
      By the way,maybe your problem is the "main" function,please check your code ,and make sure there's just one main function.
      Good luck! 
      
    • Alex

      Sounds like you have function main() declared twice, once at line 13 and once at line 24.

  • Adam Sinclair

    When I run this with Visual C++ 2008, the console opens up and it doesn’t say anything. Only says:

    Press Enter to continue…

  • sega

    When assigning a number to “x” I can’t assign the number “9999999999” to it. I figure that it is too large of a number. Is there a way to get around this?

    • senthil.cp

      hi sega,

      i have newly registered today only.
      and i have found this great website to learn c++
      all the credit to alex

      please check if my solution suits your problem


      double x = 9999999999;
      cout << setprecision(16);
      cout << "value =" << x;

    • Alex

      Use the type “long” instead of “int”. We cover this (and other types) in more detail in lesson 2.4 -- Integers.

  • Solomon Homicz

    I’ve got a problem nobody else seems to have. I’m following this tutorial with both an IDE and a text editor/command terminal. I’m running Ubuntu 10.04 with Qt Creator for an IDE, and gedit for an editor.
    When I compile the gedit version of the program manually using “g++ -o first first_C_prog.cpp” it runs and works just fine.
    When I build essentially the same code in the IDE it builds fine and runs but when I put in a number and hit enter it just goes to a new line. It doesn’t display anything back to the screen and keeps running, I have to kill it manually.
    Here’s the code, the only difference is in the manually compiled version I remove the #include Qtcore (seems like the same thing as stdafx.h).

    I’m going to dig into the IDE help next, and see if I can figure it out. I’m an engineering student and have been programming extensively in Fortran, so an editor and terminal is just fine by me, but I think an IDE is going to be essential if I want to make a jump to GUI applications.
    The professors say “if you can program in Fortran you can program in anything”, and it seems like C++ is the backbone of just about everything. Most people don’t care about things like Romberg integration or finite difference in a 3d matrix they just want a pretty window on their computer screen that gives them an answer. So, I’m off to learn C++ and this is the best tutorial I’ve found, thanx Alex.
    Anybody have suggestions on how to make this IDE behave?

    • Darren

      awww fortran - like the grandparent who refuses to die and tries to dress up like the kids with their fancy dynamic memory allocation, object orientated design, easy to use and format file i/o, smart-pointers, lambdas, …. which is just awkward for everyone concerned.

  • Jack

    It doesn’t seem to like words. Whenever you type your name in it gives you a bunch of numbers back… is there anything I can do?

    • adam

      There are several variable types in C++, in this case you’re declaring an integer variable(a variable that only stores numbers) so when you’re trying to output that variable it gives you crazy stuff.

    • Gizmo

      Hello, Jack you wrote this.

      #include
      #include

      int main()

      {
      using namespace std;

      cout << "Please enter your age:" <> x;
      cout << "Please enter your name:" << endl;
      int y;> y;
      cout << "Hello " << y << ", you are " << x << "-years-old." << endl;

      return 0;

      }

      All you have to do is change (int y; to char y [20];) I dont know thats this is the best way but it works for me.

      • Gizmo

        Sorry, I forgot the HTML tags lets try again.

        Hello, Jack you wrote this code.

        I hope I used the tags right if not sorry.

  • Matt F

    I keep getting an error message: error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    and error C2065: ‘cout’ : undeclared identifier
    and error C2065: ‘endl’ : undeclared identifier
    I don’t know why the first one getting numbers worked fine but this one does not at all, all i tried to do was erase the old stuff and enter the new stuff.

  • Ok_im_confuzed_about

    Ok so if your values are assigned to a random memory address if we make the value just x then how will you find it?

  • Michael M

    Alex, you are amazing. Thank you so much for writing these tutorials.

    I’ve spent almost two hours reading (and re-reading until I made sure I understood what you are trying to say) chapter 1.3 and below. That might seem like a lot of time, but I want to know 100% what I’m doing.

    I’m 14 years old and one day I’d love to work at a job having to do with programming (I’m looking at Valve Software right now). I knew nothing at all about C++, but very little Java, so I thought I should start here. Hopefully these tutorials will give me a good start, and I will continue to learn and practice C++ until I reach my goal. I understand that making games with C++ may be very different from what you’re teaching, but like I said, I’m hoping these tutorials will give me a good start.

    Excuse my typing, it’s 2:40 AM and I’m a bit tired. I remembered what you mentioned at the beginning of the tutorial about being tired and/or unhappy.

    Can’t wait for tomorrow!

  • rose

    Alex,
    do this #include alone work?
    y they r nt giving anything aftr tht?
    what does #include alone mean?

    Thanks

  • Jason

    Hi Alex, i am new to C++, please could you explain to me why you used the following lines:

    y = 4; // 4 evaluates to 4, which is then assigned to y
    y = 2 + 5; // 2 + 5 evaluates to 7, which is then assigned to y

    as later you say that y=7 which it does …but if y=4 ..then y = 2 + 5 = 7
    why did we have to use y = 4 ?

    regards,
    Jason

    • BR

      The idea was to show that if you re-assign a value to Y, then it will change.

  • Thank you who ever wrote this. Gave a very well explanation on wtf was going on. C is similar but cpp makes variables much simpler

  • Hey Alex, great site you have here! I was taking a C++ class years ago, but as soon as we got to pointers I gave up. Since then, I have increased my knowledge a bit, at least with python / javascript, so I figured I would give C++ another go. Anyways, im learning a lot more here then I did in school, so thanks for the site!

    Also, as far as pausing is concerned, I read this technique somewere -

    They said their reasoning is it would be cross platform compilable, because pause.exe is windows specific, and also if someone / something were to tamper with pause.exe, executing pause.exe could be dangerous.

    It seems to work well, what are your thoughts / opinions on it?

    • It’ll work in the majority of cases, and yes, it’s better than using pause.exe.

      The only time it’ll fail is if there are extra characters in the input buffer -- _getch() will read them and not stop for more input.

      I present a slightly improved version of this in lesson 0.7 -- a few common cpp problems that fixes that particular issue.

      Sadly enough, the pausing issue is by far the most common topic on this site. πŸ™‚

  • Leo

    So, it is optimal to use the minimum amount of variables, when creating a program, to make it ‘light’ on resources (RAM)?

  • Justin

    Hi alex i would like to ask you somthing when i put:

    int x;
    x = 5

    it gives me this error 25 D:\Dev-Cpp\main.cpp expected constructor, destructor, or type conversion before ‘=’ token

    and i am greatly confused plz help

    Thankz

    Justin
    C++ learner

  • Noah

    I made this

    And it worked!!!

  • fluxx

    Would this work? thank you!

    • Tyler

      hey fluxx,

      As soon as i saw your code i went at it trying to fix it. and to my pleasent suprize, i got it working.

      here is the perfected code:

      first of all, the whole “int caculate” part was compelely useless and unessary. second, “useing namespace std;” is suppost to be affter “int main ()”. third, many of your slash brackats are wrong, when useing cout, all slash brackets are facing the left . About the “system (“puase”)” part near the end, depending on what compiler you are useing you may not need it to be there. i’m useing a compiler that requires me to input a puase code. but even if your compiler dose not need it, it shoulden’t hurt anything.

      • Proof that ive actually learned something from this tutorial although in c I can make it so you can type booth the numbers on the same line but Im still learning both languages at the same time XD

  • Lumos

    Try to use system() as small as possible. It will be better (in our situation) to use getch(); whicl allocated at conio.h

  • You cuold have probably went into a little more detail about those 2 functions but you did a good job of getting us on the right track…to start with.

  • Whenever I try to compile the program that outputs the input variable…

    It gives me this error..

    1>LINK : fatal error LNK1104: cannot open file ‘kernel32.lib’

    Any ideas?

  • abdy

    hey, every time i run this code i keep getting 5 for the answer.
    my guess is that its keeping x stored from the previous exercise, but shouldnt the cin.clear that you said to use get rid of that?

    # include

    int main ()
    {
    using namespace std;
    int y; // declare y as an integer variable
    y = 4; // 4 evaluates to 4, which is then assigned to y
    y = 2 + 5; // 2 + 5 evaluates to 7, which is then assigned to y

    int x; // declare x as an integer variable
    x = y; // y evaluates to 7, which is then assigned to x.
    x = x; // x evaluates to 7, which is then assigned to x (useless!)
    x = x + 1; // x + 1 evaluates to 8, which is then assigned to x.
    cin.clear();
    cin.ignore(255, ‘\n’);
    cin.get();
    return 0;
    }

    • Hi abdy. This program shouldn’t output anything since you don’t have any cout statements, so I am not sure how you “keep getting 5 for the answer”. If you are getting output, then I suspect you’re actually compiling and running a different project. Some compilers let you keep multiple projects open simultaneously. Make sure the project you want to compile is the active one (usually, right click on it and choose “set as active project” or something similar).

      The cin.clear(); cin.ignore(255, ‘\n’); cin.get() lines just force the program to pause at the bottom so you can see the output before the window closes.

  • me

    I got a little prob here:
    when i run the program it asks me to enter a number and when i do and press enter, the program closes.. ?
    (i use Dev-C++ 4.9.9.2)

    Thx,
    Me

  • renu

    My question is same as Chucks. I tried this and it is printing -858993460 . Why is it printing a particular number if it is a garbage value? Is there a specific reason for that? I tried it 3-4 times and every time it prints -858993460 .
    Thanks,
    Renu

    • Because this variable is not allocated dynamically, it’s being allocated on the stack. Lots of stuff is put in the stack, including function call information, return addresses, etc… I presume (and this is just an educated guess) that the fact that we are all seeing the same number (-858993460) has something to do with the way the program or the OS is setting up the stack before the program begins executing. Perhaps the OS is cleaning out the stack to ensure that we don’t “recover” sensitive information from a prior program’s execution?

      As an aside, although -858993460 seems like a really bizarre number, it’s actually just 0xCCCCCCCC in hex (which is bit pattern 1100 1100 1100 1100 1100 1100 1100 1100).

    • Tom

      This is feature of building debug C++ software with Visual Studio. Anything you don’t initialise yourself is set to 0xCCCCCCCC (interpreted as -858993460 if it’s an int).

      Try switching the build type from debug to release, and the value will be truly uninitialised and may change each time you run it.

  • Chuck Nelson

    Why the value of -858993460 when displaying an uninitialized int?

    It is not the min int. Is there a reason it is this value?

    Thank you!

    • Memory is really just a sequence of binary bits strung together, and memory gets reused often. So your int variable x might use the same memory location as some other variable was using just a moment ago. If the variable x is not initialized, it “inherits” (in the non object-oriented sense) whatever value was there previously.

      For example, let’s say there was 8 bits of memory that had this value: 0000 0101.

      If you declared char chValue, and the variable chValue was assigned to this memory address, then chValue will start with the “uninitialized” value 5, because 0000 0101 binary = 5 decimal.

      As a consequence of this, you never know what value an uninitialized variable will print because it depends on whatever happens to already be in memory the variable is using. It may change every time you run the program. It may change only occasionally. But you can always count on it being something you don’t want!

  • first the line looks wrong
    it should be cout >> x; not cout > x;

    Second, the prg closes if you are using VS2005 or a similar IDE. VS2005 creates a new console window when the program starts and closes it as soon as the program finishes. The code executed perfectly. Just that as soon as it prints the output, the program has finished and it closes leaving you no time to see it. you need to make it pause using a “cin” function.

    i wrote my own terminating code:

    //for terminating the application
    	cout < > exitapp;
    	cout < < "terminating" <
  • Lol

    It doesent Work.

    When is Try it says
    inter number here i enter the number and the Prg Closes πŸ™

    • csvan

      Lol, which IDE and which OS are you using? Under Windows, you can use a function called system(“PAUSE”) in order to pause the program before it goes on (in your case, exits).

      In your case, you then first need to write the following in the beginning of the program:

      This will include the C standard library into your program.

      Then, before the return statement in main(), add system(“PAUSE”), as such:

      That should do it. However, the bad thing here is that I think this works ONLY on Windows…not good! Also, I have heard that the system() function is very unsafe and should generally be avoided in professional projects, which is perhaps not so important here because you are just studying.

      Hope that helps! If you need more help you can mail me (csvanefalk@hushmail.me) or of course ask the owner of the site (Alex). Me and Alex are not affiliated in any way, I would just like to help out πŸ™‚ Dont forget to give the props to Alex for his great site though!

  • Kyle

    When i try and run the code to enter a number and have it be displayed it isn’t working right. A box opens and it asks my number and i type it in and the box just closes. Not sure what im doing wrong.

    • Ravi

      Try the following Kyle, it will surely work:

      Ravi..

      • csvan

        No, unfortunately it will not. His problem was that the program closed immediately after input. It is most likely because he has an IDE which breaks program execution immediately after main() returns 0. As such, he would need to either use a pause function such as system(“PAUSE”) to prompt the user to press enter, before the program breaks execution.

    • Darren

      If using Visual Studio then this is the default behaviour; the program exits and terminates the console window immediately. You can remedy this by going to the Property Sheet for the VS project (right-click the solution name in the "Solution Explorer" pane and click "Properties" at the bottom of the sub-menu) select linker -> system and the first field in the sheet should read "SubSystem" with a drop-down menu icon. Click the icon and select a "Console" subsystem and okay the change. You will have to recompile project (shortcut key f7) but now if you run it using ctrl-f5 the console will hang after the program has finished, allowing you to read the output. Note that pressing f5 alone will not make the console hang.

    • Satwik

      just use getch(); ,  included in the conio.h library πŸ™‚

  • Lol

    The Code:

    #include “stdafx.h”
    #include

    int main()
    {
    using namespace std;
    cout > x; // read number from console and store it in x
    cout

    It Dosent Work

    • newuser

      When you use the cout call from the output stream the directional indicator needs to be < . The > is for the cin call from the library.

    • Ravi

      • csvan

        You forgot to initialize x (ie. x = 7;)! I also think it is better if you put using namespace std; OUTSIDE main, to make it global.

        • Quinn

          I disagree. This can very easily in larger programs cause cryptic errors from name conflicts. Keeping using namespace within functions limits it’s scope, and thus limits its potential for causing problems. The safest, though, is to simply always refer to the namespaces, i.e. “std::cout << x” instead.

    • venki

      cout > x;
      is wrong usage. " << " this operator is used to output the value

Leave a Comment

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