Search

1.3 — Introduction to variables

Data

In lesson 1.1 -- Statements and the structure of a program, you learned that the majority of instructions in a program are statements, and that statements are grouped into functions. These statements perform actions that (hopefully) generate whatever result the program was designed to produce.

But how do programs actually produce results? They do so by manipulating (reading, changing, and writing) data. In computing, data is any information that can be moved, processed, or stored by a computer.

Key insight

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

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

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

Objects and variables

All computers have memory, called RAM (short for random access memory), that is available for your programs to use. You can think of RAM as a series of mailboxes that can be used to hold data while the program is running. A single piece of data, stored in memory somewhere, is called a value.

In some older programming languages (like Apple Basic), you could directly access these mailboxes (a statement could say something like go get the value stored in mailbox number 7532).

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

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

Author's note

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

Variable instantiation

In order to create a variable, we use a special kind of declaration statement called a definition (we’ll clarify the difference between a declaration and definition later).

Here’s an example of defining a variable named x:

At compile time, when the compiler sees this statement, it makes a note to itself that we are defining a variable, giving it the name x, and that it is of type int (more on types in a moment). From that point forward (with some limitations that we’ll talk about in a future lesson), whenever the compiler sees the identifier x, it will know that we’re referencing this variable.

When the program is run (called runtime), the variable will be instantiated. Instantiation is a fancy word that means the object will be created and assigned a memory address. Variables must be instantiated before they can be used to store values. For the sake of example, let’s say that variable x is instantiated at memory location 140. Whenever the program then uses variable x, it will access the value in memory location 140. An instantiated object is sometimes also called an instance.

Data types

So far, we’ve covered that variables are a named region of storage that can store a data value (how exactly data is stored is a topic for a future lesson). A data type (more commonly just called a type) tells the compiler what type of value (e.g. a number, a letter, text, etc…) the variable will store.

In the above example, our variable x was given type int, which means variable x will represent an integer value. An integer is a number that can be written without a fractional component, such as 4, 27, 0, -2, or -12. For short, we can say that x is an integer variable.

In C++, the type of a variable must be known at compile-time (when the program is compiled), and that type can not be changed without recompiling the program. This means an integer variable can only hold integer values. If you want to store some other kind of value, you’ll need to use a different variable.

Integers are just one of many types that C++ supports out of the box. For illustrative purposes, here’s another example of defining a variable using data type double:

C++ also allows you to create your own user-defined types. This is something we’ll do a lot of in future lessons, and it’s part of what makes C++ powerful.

For these introductory chapters, we’ll stick with integer variables because they are conceptually simple, but we’ll explore many of the other types C++ has to offer soon.

Defining multiple variables

It is possible to define multiple variables of the same type in a single statement by separating the names with a comma. The following 2 snippets of code are effectively the same:

is the same as:

When defining multiple variables this way, there are two common mistakes that new programmers tend to make (neither serious, since the compiler will catch these and ask you to fix them):

The first mistake is giving each variable a type when defining variables in sequence.

The second mistake is to try to define variables of different types in the same statement, which is not allowed. Variables of different types must be defined in separate statements.

Best practice

Although the language allows you to do so, avoid defining multiple variables in a single statement (even if they are the same type). Instead, define each variable in a separate statement (and then use a single-line comment to document what it is used for).

Summary

In C++, we use variables to access memory. Variables have an identifier, a type, and a value (and some other attributes that aren’t relevant here). A variable’s type is used to determine how the value in memory should be interpreted.

In the next lesson, we’ll look at how to give values to our variables and how to actually use them.

Quiz time

Question #1

What is data?

Show Solution

Question #2

What is a value?

Show Solution

Question #3

What is a variable?

Show Solution

Question #4

What is an identifier?

Show Solution

Question #5

What is a type?

Show Solution

Question #6

What is an integer?

Show Solution


1.4 -- Variable assignment and initialization
Index
1.2 -- Comments

374 comments to 1.3 — Introduction to variables

  • 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 all code inside code tags: [code]your code here[/code]