Navigation



2.1 — Basic addressing and variable declaration

Addressing memory

This lesson builds directly on the material in the section “A first look at variables“.

In the previous lesson on variables, we talked about the fact that variables are names for a piece of memory that can be used to store information. To recap briefly, computers have random access memory (RAM) that is available for program to use. When a variable is declared, a piece of that memory is set aside for that variable.

The smallest unit of memory is a binary digit (bit), which can hold a value of 0 or 1. You can think of a bit as being like a traditional light switch — either the light is off (0), or it is on (1). There is no in-between. If you were to look at a sequential piece of memory, all you would see is …011010100101010… or some combination thereof. Memory is organized into individual sections called addresses. Perhaps surprisingly, in modern computers, each bit does not get it’s own address. The smallest addressable unit of memory is a group of 8 bits known as a byte.

The following picture shows some sequential memory addresses, along with the corresponding byte of data:

Memory Addressing

Because all data on a computer is just a sequence of bits, we use a data type to tell us how to interpret the contents of memory in some meaningful way. You have already seen one example of a data type: the integer. When we declare a variable as an integer, we are telling the computer “the piece of memory that this variable addresses is going to be interpreted as a whole number”.

When you assign a value to a data type, the computer takes care of the details of encoding your value into the appropriate sequence of bits for that data type. When you ask for your value back, the program “reconstitutes” your number from the sequence of bits in memory.

There are many other data types in C++ besides the integer, most of which we will cover shortly. As shorthand, we typically refer to a variable’s “data type” as it’s “type”.

Declaring a variable

In the “basic C++” section, you already learned how to declare an integer variable:

int nVarName; // int is the type, nVarName is the name of the variable

To declare variables of other data types, the idea is exactly the same:

type varName; // type is the type (eg. int), varName is the name of the variable

In the following example, we declare 5 different variables of 5 different types.

bool bValue;
char chValue;
int nValue;
float fValue;
double dValue;

It’s that simple. (Well, almost — there are a few things you can’t name your variables, which we’ll talk about in the next section)

You can also assign values to your variables upon declaration. When we assign values to a variable using the assignment operator (equals sign), it’s called an explicit assignment:

int nValue = 5; // explicit assignment

You can also assign values to variables using an implicit assignment:

int nValue(5); // implicit assignment

Even though implicit assignments look a lot like function calls, the compiler keeps track of which names are variables and which are functions so that they can be resolved properly.

Declaring multiple variables

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

int nValue1, nValue2;
int nValue1;
int nValue2;

You can also assign them values on the declaration line:

int nValue1 = 5, nValue2 = 6;
int nValue3(7), nValue4(8);

Which is effectively the same as:

int nValue1 = 5;
int nValue2 = 6;
int nValue3 = 7;
int nValue4 = 8;

There are three mistakes that new programmers tend to make when declaring multiple variables in the same statement.

The first mistake is declaring each variable as int (or whatever type it is) in sequence. This is not a bad mistake because the compiler will complain and ask you to fix it.

int nValue1, int nValue2; // wrong (compiler error)

int nValue1, nValue2; // correct

The second error is to try to declare two variables of different types on the same line, which is not allowed. Variables of different types must be declared in separate statements. This is also not a bad mistake because the compiler will complain and ask you to fix it.

int nValue1, double dValue2; // wrong (compiler error)

int nValue1; double dValue2; // correct (but not recommended)

// correct and recommended (easier to read)
int nValue1;
double dValue2;

The last mistake is the dangerous case. In this case, the programmer mistakenly tries to initialize both variables by using one assignment statement:

int nValue1, nValue2 = 5; // wrong (nValue1 is uninitialized!)

int nValue1 = 5, nValue2 = 5; // correct

In the top statement, the nValue1 variable will be left uninitialized, and the compiler will NOT complain. This is a great way to have your program intermittently crash and produce sporadic results.

The best way to remember that this is wrong is consider the case of implicit initialization:

int nValue1, nValue2(5);

This makes it seem a little more clear that the value 5 is only being assigned to nValue2. The explicit assignment case is no different.

Where to declare variables

Older C compilers forced users to declare all of the variables in a function at the top of the function:

int main()
{
    // all variable up top
    int x;
    int y;

    // then code
    using namespace std;
    cout << "Enter a number: ";
    cin >> x;

    cout << "Enter another number: ";
    cin >> y;

    cout << "The sum is: " << x + y << endl;
    return 0;
}

This style is now obsolete. C++ compilers do not require all variables to be declared at the top of a function. The proper C++ style is to declare variables when and where they are needed:

int main()
{
    // then code
    using namespace std;

    cout << "Enter a number: ";
    int x; // we need x starting here.
    cin >> x;

    cout << "Enter another number: ";
    int y; // we don't need y until now
    cin >> y;

    cout << "The sum is: " << x + y << endl;
    return 0;
}

This has quite a few advantages. First, variables that are declared only when needed are given context by the statements around them. If x were declared at the top of the function, we would have no idea what it was used for until we scanned the function and found where it was used. Declaring x amongst a bunch of input/output statements helps make it obvious that this variable is being used for input and/or output.

Second, declaring a variable only where it is needed tells us that this variable does not affect anything above it, making our program easier to understand and requiring less scrolling. Finally, it reduces the likelihood of inadvertently leaving a variable uninitialized, because we can declare and then immediately initialize it with the value we want it to have.

Rule: Declare variables where they are needed.

2.2 — Keywords and naming identifiers
Index
1.11 — Comprehensive quiz

62 comments to 2.1 — Basic addressing and variable declaration

  • [...] the lesson on basic addressing and variable declaration, you learned that you could assign values to variables in two ways: explicitly and [...]

  • Abhishek

    That was easy :D

  • emmm..

    and why you use:


    using namespace std;

    I don’t use it…

    • using namespace std;

      allows you to access anything that lives in the std namespace without having to use the std:: prefix. It’s useful for using in conjunction with cin and cout so you can type “cin” or “cout” instead of “std::cin” or “std::cout”.

      If you

      #include <iostream.h>

      , then cin and cout are not defined as being in the std namespace, and you won’t need it. However, it’s better to

      #include <iostream>

      , where cin and cout are defined inside the std namespace. In this case, you can use the using statement to make your code simpler and easier to read.

      • Take a look at this screenshot I took of your comment. What are you meaning by If you #include , *snip* it’s better to #include ,

        It’s showing the exact same thing. I’ve noticed this a couple other times in comments mostly but even in the tutorial. Is there supposed to be more showing? (I’ve checked in FF3 and IE7 and both display the same).

        Other than that little thing this tutorial has been great so far! I really like how you’re moving along in the tutorial with small bits of info here and there rather than throwing the whole subject (of say variables) at me all in one big lump!

        Thanks alot for taking the time to create this site.

        • Although I couldn’t see your screenshot (I get a page load error), I was seeing blanks after the #include as well. The problem is that this website software (WordPress) assumes you’re writing HTML and not code, so unless you tell it otherwise, it thinks <iostream> is an HTML tag of some sort — so it just eats it.

          I’ve fixed the above comment.

          • Boxchan

            However, Alex, you really should put the namespace std thing before all the functions, but after the includes. This way, you just have to type it once, becuase it is in the whole script then.

  • [...] 2.1 — Basic addressing and variable declaration [...]

  • [...] 2.1 — Basic addressing and variable declaration [...]

  • Jesse

    “This is not a bad mistake because the compiler will complain and ask you to fix it.”
    Shouldn’t this say:
    “This is a bad mistake because the compiler will complain and ask you to fix it.”

    • Nope. In my view, anything the compiler catches is not a bad mistake because the compiler points out exactly where the error is. Those tend to get fixed immediately. The bad mistakes are the ones the compiler doesn’t catch. Those are the ones that are likely to creep into production code (code released to the public).

  • Argon

    Hi, and thank you for a very informative and easy-to-read tutorial.

    One question to the “define variables along the way”.. I have a love for using this type of defining:

    type foo()
    {
    type tDescriptiveName(alternatively a default value); // Description
    type tDescriptiveName(alternatively a default value); // Description
    type tDescriptiveName(alternatively a default value); // Description
    type tDescriptiveName(alternatively a default value); // Description

    [... function code ...]
    }

    Find this more tidy. And if var (witch it often is) are used more than once, “top description” will give a clear meaning.
    Any sense in this?

    • Well, if it’s your code you’re welcome to do whatever you like. :) But generally, the declare your variables at the top style of declaration is considered deprecated in C++. My personal experience has taught me that it leads to tougher to read/understand code, even when they are commented.

      One issue with declare-at-the-top style of declaration is that you often have to scroll up to find out whether a variable is a local variable (declared in the function) or a function parameter. Declare-when-needed often doesn’t suffer from this wasted energy, since the majority of variables in a function will be declared when needed and used immediately thereafter.

      • Bradley

        Your second point, that you need to scroll up to find out whether a variable is a local variable or a function parameter is solved simply by following some common sense programming guidelines. Use prefixes on items to indicate what they are. For example;

        //pv prefix means it is a parameter value
        //lv prefix means it is a local variable
        
        int add(int pvVal1, int pvVal2)
        {
          int lvResult = pvVal1 + pvVal2;
          return lvResult;
        }
        

        This method – or something like it – has been the standard at almost every company I have worked with in my 15+ years as a consultant. This notation, along with the use of meaningful variable names, makes most claims to one method of declaring variables being superior to the other pretty meaningless in my opinion.

  • CuView
    int main()
    {
       using namespace std;
    
       int x;
       cin >> x;
    
       return 0;
    }
    

    Does the ‘x’ variables above is initialized or not?
    How to know weather the variables is initialized or uninitialized?

    • When x is declared, it is not intitialized. After the cin statement, x may or may not be initialized depending on whether the user entered a valid number or not. In this example, it would be a good idea to declare x and assign it to 0 immediately:

      int x = 0;
      

      There is no sure-fire way of telling whether a variable is initialized or not. Consequently, it’s a good idea to always initialize your variables when they are declared. That way, you won’t have to guess.

  • Ali

    what is the difference between the explicit assignment and the implicit assignment ? what does each one differ than another? where should I use them?

  • Bob

    What is the fundamental difference between explicit and implicit assignment? Is there any reason to use one over the other? Is there any difference between ‘int nValue = 50′ and ‘int nValue(50)’? Does the compiler treat them differently? Or is the end result always the same regardless; nValue = 50.

  • Ben

    I used the following code:

     int x, y = 5; 

    and it worked just fine, but the tutorial said it would not compile. Now I’m confused..

    • Actually if you read closely, I said it was dangerous, not that it wouldn’t compile. It WILL compile, but x will be uninitialized. Most new programmers assume that it will be initialized to 5, which is not the case. That’s why this is particularly dangerous.

  • Tate

    Would initializing the intiger x as it is taken from input work?
    e.g.

    cin >> int x;
  • CJ

    When you say,

    “You can also assign them values on the declaration line:
    int nValue1 = 5, nValue2 = 6;
    int nValue3(7), nValue4(8);

    Which is effectively the same as:
    int nValue1 = 5;
    int nValue2 = 6;
    int nValue3 = 7;
    int nValue4 = 8;”

    Shouldn’t the last two lines be int nValue3(7) and int nValue4(8) because they are supposed to be implicit?

  • Hi, alex.
    can you tell me when I define an int like

    int i;

    where is the information like the type and the address of i placed?

  • Fluke

    Hi Alex,
    Great tutorial so far!

    A question about declaring variables where they are used.
    I am a bit old-style programmer and i cant find the arguments for declare variables when used to be so good.

    Here is my reasoning (proove me wrong, so i can change my style :)
    Lets see if we have 1000 lines of code. We have a function of 300 lines somewere inside (among other functions).
    If we use function variables more than once inside that function, and they are declared on their first use, isnt it harder, later on, to find out which one is global and which is declared within those 300 lines?
    Or just if we had all function variables just under function name – you can see on first glance which one is there and which one is global?

  • Lilwolf

    I have a question…

    I’m learning Computer Science through a college class, and we were taught to declare variables in the header files under the private section with functions under public…

    Why? I’m a little confused and eager to learn, and sadly my professor doesn’t seem to be able to explain things too well. Help please!! :)

  • Gigith

    “computers have random access memory (RAM) that is available for program to use.”
    That should be “programs” or “the program”.

  • AsianBorat

    YES!!!! This is exactly what I was looking for! (I was wondering about the “int nValue1, nValue2 = 5; // wrong (nValue1 is uninitialized!)” bit when I was searching for an answer on google)

    I also learned a whole lot more about declaring ints than from other tutorials.

  • Shaun

    so then by making new functions such as:

    int read( int x, int y)
    {
    
    	return x + y;
    }

    is kind of extra work if we can just declare the variables within the Main() function, and get the same output? for example:

    int main()
    {
    	using namespace std;
    	int x;
    	cout << "enter first number here" << endl;
    	cin >> x;
    	int y;
    	cout << "enter second number here" << endl;
    	cin >> y;
    	cout << x + y << endl;
    	return 0;
    }

    this doesnt require any other functions to add 2 numbers from a user and give a result. but in the chapter 1 comprehension quiz we needed 2 functions to do what this single Main() function can do without the hassle. am i missing something? or does this seem so much easier? or maybe that’s why you made this more clear in the next chapter? just want to note, i do understand making a function to do this for us is beneficial for multiple addition problems, but for a single one, i find this is much simpler.

  • prafull.badyal

    gud..thanks to sir alex

  • Kostas81

    A quick question:

    Alex wrote: “The last mistake is the dangerous case. In this case, the programmer mistakenly tries to initialize both variables by using one assignment statement.

    1 int nValue1, nValue2 = 5; // wrong (nValue1 is uninitialized!)
    2
    3 int nValue1 = 5, nValue2 = 5; // correct

    In the top statement, the nValue1 variable will be left uninitialized, and the compiler will NOT complain. This is a great way to have your program intermittently crash and produce sporadic results.”

    But in section 1.3, “A first look at variables (and cin)” Alex had wrote:

    “A variable that has not been assigned a value is called an uninitialized variable. Uninitialized variables are very dangerous because they cause intermittent problems (due to having different values each time you run the program). This can make them very hard to debug. Most modern compilers WILL print warnings at compile-time if they can detect a variable that is used without being initialized.”

    And few lines before he wrote:

    “Some newer compilers, such as Visual Studio 2005 Express will pop up a debug error message if you run this program from within the IDE.” (He means a program with an uninitialized variable.)

    So, why here the compiler will not complain about the uninitialized variable???
    (And can someone tell me, “wrote” is the past tense for “write” or not? :D)

  • [...] by admin on December 18, 2011 in C++ · 0 Comment As you learned in the lesson on basic addressing, memory on modern machines is typically organized into byte-sized pieces, with each piece having a [...]

  • [...] you learned in the lesson on basic addressing, memory on modern machines is typically organized into byte-sized pieces, with each piece having a [...]

  • [...] the lesson on basic addressing and variable declaration, you learned that you could assign values to variables in two ways: explicitly and [...]

  • Careena

    I wrote the program like this…
    #include
    using namespace std;
    void main()
    {
    int a=5,b(5);
    cout<<a<<b;
    }
    But when I ran this program errors occured.what's wrong in this program?

    • Mohammad Abouchama

      I don’t know if you found the answer by now but I’ll help just in case.

      The main() function must have a return type of int. So it should be like this int main(). Whereas yours has void.
      It can have several other forms such as:

      int main(void)
      int main()
      int main(int argc, char *argv[])
      int main(int argc, char ** argv[])

      But all must return an int.
      So basically just replace void with int, and make this statement return 0; as your last statement.

  • wholesaleearrin

    Vestidos para ocasiones especiales 2013

  • wholesaleearrin

    Vestidos de boda al por mayor | baratos Vestidos de novia barato de la boda | Vestidos de boda – Simply nupcial

  • kijonrwslows

    Bröllopsklänningar , Beach Wedding Klänningar

  • kijonrwslows

    have the ability to take further benefit for a completely new American passion:saving with the help of online researching!
    Suggestion 1:Do not buy Craigslist and ebay.We many know sale seem want such very much, and its basic get trapped in this emotion about auction.Point is, auction web-sites like Craigslist and ebay and Ubid have grown to be saturated utilizing buyers AND ADDITIONALLY sellers, so almost any discount located is easily sought just by re-distributors who start being active .their personal markups for the purchase.The via the internet marketplace contains enough people in existence that you could end up spending many extra dollars for those same things obtained in your hometown mall! Dont make it possible for your emotions become involved these will not be the best places with the aware consumer.
    Suggestion 2:In no way pay retail store.Take this unique scenario:You look for something you need to buy, maybe the hottest craze or maybe fad like the Ipod.In the event you really pay thhave the ability to take further benefit for a completely new American passion:saving with the help of online researching!

    Suggestion 1:Do not buy Craigslist and ebay.We many know sale seem want such very much, and its basic get trapped in this emotion about auction.Point is, auction web-sites like Craigslist and ebay and Ubid have grown to be saturated utilizing buyers AND ADDITIONALLY sellers, so almost any discount located is easily sought just by re-distributors who start being active .their personal markups for the purchase.The via the internet marketplace contains enough people in existence that you could end up spending many extra dollars for those same things obtained in your hometown mall! Dont make it possible for your emotions become involved these will not be the best places with the aware consumer.

    Suggestion 2:In no way pay retail store.Take this unique scenario:You look for something you need to buy, maybe the hottest craze or maybe fad like the Ipod.In the event you really pay the charge that Apple is providing? No! You’ll find many specials and coupons for ones same purchase through typing, for instance, ipod vouchers int The search engines.Spend a little time searching via the top twenty to something like 20 results, youre sure to obtain the same product on a significant price cut.Sometimes, by writing a online survey or becoming a member of an mail list, youll receive additional savings a lot of times you may also get any product at zero cost!

    Suggestion 3:Overcome your fast gratification motivation.Just say it, buying an issue always produces a beneficial feeling while you cant hold on to get pleasure from that fresh purchase.Anything youre buying in the mall to make the same superior feeling may well usually end up found for just a huge lower price online.You have to be ready wait for those short 2-5 days so it takes designed for shipping.Its undeniably worth all the savings to in a position to control any emotions and hold-up until this arrives via UPS!

    Suggestion 4:Look out for excessive shipment charges.Many situations retailers cut their costs to find the sale ; however , charge alot more for delivery.Make sure to confirm the remaining cost to guarantee you didnt have any unwarranted costs.You will typically find also shipping put up at several online token sites.Sometimes this shipping can certainly cost a lot more than your order!

    Suggestion 5:On the internet coupons:Were you conscious of online voucher websites which happen to have discount and additionally promotion computer codes to many internet retailers? These varieties websites have always contemporary discount delivers arranged just by category or simply store, to help you always look for something available for purchase.Its not really a way to have a good put up but you can also find some on the free shipping and delivery offers mentioned in word of advice 4.You need to be careful to be sure for a bonus coupon before doing any word wide web purchase.Its an easy way to uncover extra benefits.

  • aditya.dharmasagar

    what is the difference between using “using namespace std” globally and locally ?? it would be easy if we declare it globally right ?? so that in every function we need not declare it again and again ??

  • aditya.dharmasagar

    what is the difference between using “using namespace std” globally and locally ?? it would be easy if we declare it globally right ?? so that in every function we need not declare it again and again ???

  • nrayeinmmi

    trate on the quite a few advertisements that to appear on your web site.This may be a put off for lots of visitors who go to your websites.They can look elsewhere because the irritating pop-ups or perhaps adverts of which keep appearing in the future.So how might one characteristics consequences involving free hosting services? By deciding on paid though cheaper web host services certainly! That makes us to another location question where you get cheap web host? There are numerous companies that comes with cheap internet hosting solutions.However there are certaitrate on the quite a few advertisements that to appear on your web site.This may be a put off for lots of visitors who go to your websites.They can look elsewhere because the irritating pop-ups or perhaps adverts of which keep appearing in the future.So how might one characteristics consequences involving free hosting services? By deciding on paid though cheaper web host services certainly! That makes us to another location question where you get cheap web host? There are numerous companies that comes with cheap internet hosting solutions.However there are certain tricks to assist you to decide that this best one for your needs is.Space.The earliest requirement is certainly space.If however, you have recordsdata that occupy an excessive amount disk place or bandwidth, then its far better choose an agency that creates a large site that allows downloads likewise.Email.Most web hosting service companies will give email support 100 % free.One thing to not overlook while considering where we can get cheap web host is that will storage together with viewing with emails is bound to take up disk spot.Customer Company.Most web host service services are notorious on their customer service.Therefore, it contributes greatly to purchase a vendor that features good assist.Downtime Challenges.The very last thing you want is the platform for your website experiencing downtime troubles.So while in need of where we can get cheap web hosting service consider the volume of uptime the host brings you.Uptime will need to ideally get 99.5% to help qualify a fabulous hosting provider to be good.So, your site will likely be inaccessible for at 7.2 minutes daily.Want to receive Cheap Web hosting service .

You must be logged in to post a comment.