1.3 — A first look at variables


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

A variable in C++ is a name for a piece of memory that can be used to store information. You can think of a variable as a mailbox, or a cubbyhole, where we can put and retrieve information. All computers have memory, called RAM (random access memory), that is available for programs to use. When a variable is defined, a piece of that memory is set aside for that variable.

In this section, we are only going to consider integer variables. An integer is a whole number, such as 1, 2, 3, -1, -12, or 16. An integer variable is a variable that holds an integer value.

In order to define a variable, we generally use a declaration statement. 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 an 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 any value that can be assigned to an l-value. r-values are always evaluated to produce a single value. Examples of r-values are single numbers (such as 5, which evaluates to 5), variables (such as x, which evaluates to whatever value was last assigned to it), or expressions (such as 2 + x, which evaluates to the value of x plus 2).

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). On the right side of the assignment operator, x is being used as an r-value, and will be 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.

Programmers don’t tend to talk about l-values or r-values much, so it’s not that important to remember the terms. The key takeaway 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.

Uninitialized variables

Unlike some programming languages, C/C++ does not initialize variables to a given value (such as zero) automatically (for performance reasons). Thus when a variable is assigned to a memory location by the compiler, the default value of that variable is whatever garbage happens to already be in that memory location! A variable that has not been assigned a value 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.

Uninitialized variables can lead to interesting (and by interesting, we mean 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 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.

A couple of notes 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, a possible solution to get around this issue is noted in the comments section.

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 assign values to variables when they are defined. C++ makes this easy by letting you assign values on the same line as the declaration of the variable:

This ensures that your variable will always have a consistent value, making it easier to debug if something goes wrong somewhere else.

Rule: Assign values to your variables when you define them.

What values does this program print?

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

1.3a -- A first look at cout, cin, endl, the std namespace, and using statements
1.2 -- Comments

139 comments to 1.3 — A first look at variables

  • Lol

    The Code:

    #include “stdafx.h”

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

    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.

  • 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:


      • 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.

  • 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 ( 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!

  • 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" <
  • 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!

  • 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 .

    • 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.

  • 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++


  • 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.ignore(255, ‘\n’);
    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.

  • 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?

  • 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.

  • Lumos

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

  • 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

  • Noah

    I made this

    And it worked!!!

  • 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


    C++ learner

  • Leo

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

  • 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. :)

  • 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

  • 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 ?


    • BR

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

  • rose

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


  • 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!

  • 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?

  • 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.

  • 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.


      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.

  • 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?

  • 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.

  • 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…

  • lisyhave

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

    #include “StdAfx.h”


    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”
      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.

  • 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.

      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;
      cout << a;

      return 0;

  • 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.

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


  • 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?

  • 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.

  • 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)


    int main()
    using namespace std;
    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.

  • Homesweetrichard


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


  • AIKS

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

  • 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:

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

    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.

  • 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?

  • 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.

  • 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?

  • 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

    • 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)

  • 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.

  • 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

  • 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.

  • 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.

  • 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.

  • 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.

  • 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?

    • 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.

  • chirag

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

    #include "stdafx.h"

    int main()
        int x = 5;
        x= x-2;
        int y=x;
        int z=x+y;
        int a=x+y*z;
        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.

  • gigi

    Can you add return 0 in your example?

  • Brian

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

  • 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

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

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


  • 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.

  • 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.

  • 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?

  • Rohit

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

  • 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.

  • 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?

  • daniel

    another question sir,
    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?

    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?

  • Darius

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

  • soham

    when will i be able to make a game of my own

Leave a Comment




one × one =

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