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

81 comments to 2.1 — Basic addressing and variable declaration

  • ordwaneffshuff

    look for contacts low-priced online.You will likely get numerous hits, but a minimum of you’ll have a starting factor.Visit websites, see what you should need to be able to place plus order, and keep an eye on what you discover.Eventually, you are able to narrow the selections right down to the preferred site feasible.
    Another method to find contacts cheap on the internet is through person to person.Talk for your friends who have contacts and see where they find them.Additionally, talk to members of the family and focus on what you actually hear peolook for contacts low-priced online.You will likely get numerous hits, but a minimum of you’ll have a starting factor.Visit websites, see what you should need to be able to place plus order, and keep an eye on what you discover.Eventually, you are able to narrow the selections right down to the preferred site feasible.

    Another method to find contacts cheap on the internet is through person to person.Talk for your friends who have contacts and see where they find them.Additionally, talk to members of the family and focus on what you actually hear people say.Looking to other people for this sort of information can be quite valuable because they have made use of the services and know if it’s worth your time and effort and finances.When you do it yourself, on another hand, you are doing a little learning from mistakes no matter how much online research you need to do.

    Lastly, you will find contact accessories cheap on the internet by looking to consumer web-sites.There are numerous websites out there that complete consumer homework on almost any retail purchase it’s possible you’ll make.They will help you to find the sites by yourself, but so that you can still have another person tell you if the site is effective or definitely not.Common Feeling always prevails here.

    Vision treatment and correction can certainly be pricey.Nevertheless, finding contact lenses cheap online can really help to counteract that fee.There are numerous ways to seek out online contact lenses, but using the tips in this case you will be able to get a good start on the process.Once you need to do, though, you will likely never buy contacts every other way once again.?

  • imiltsiass

    l wedding, you will want to have that sized to guarantee the fit is ideal as nicely.
    In the case of sizing being married ring, former mate a minimal tricky.You will also schedule plenty of to alter the measurements if required.The following certainly are a few tips you must follow to receive the most suitable fit an individual’s ring.
    The greatest situation designed for sizing your wedding band is so that the air flow is comfortable on temperature and additionally climate.Any varieties rather also hot or perhaps too freezing could improve or lessen your actual band size.It is actually suggested you do not size the wedding ceremony ring directly after invest in.The call needs time to l wedding, you will want to have that sized to guarantee the fit is ideal as nicely.

    In the case of sizing being married ring, former mate a minimal tricky.You will also schedule plenty of to alter the measurements if required.The following certainly are a few tips you must follow to receive the most suitable fit an individual’s ring.

    The greatest situation designed for sizing your wedding band is so that the air flow is comfortable on temperature and additionally climate.Any varieties rather also hot or perhaps too freezing could improve or lessen your actual band size.It is actually suggested you do not size the wedding ceremony ring directly after invest in.The call needs time to sit in your little finger; many people realize sizing will not be necessary just after wearing it just the summer days.High temperature, climate, and actions all see how well the actual ring might fit your finger.

    If for example the ring you’d like must end up being sized, youre able to determine the ring size at your area jewelry shop, purchasing an important ring sizer, or even getting a string at your house.

    You’re able to measure your own private finger regarding ring dimensions, however, it is far better if an individual leave it to somewhat of a professional.The thread technique isn’t really always precise, therefore, dont want to be observed upon.Jewelers most often have their personal trained individuals and professional ring sizers to start this for you will.This will always obtain the ideal size to your wedding engagement ring.After every, the perfect a wedding ring is not too perfect if it doesn’t stop here fit.

    It’s always ultimately important that your ring sizer suit comfortably on your finger, previously authorizing the actual jeweler to build your a wedding ring of that size.Have the fitting call will keep your ring do not fall off of or damage your fingers because the device is far too tight.Subsequently after proper sizes, the ring you have opted will end up completely perfect and that you will feel self-assured in sporting in and in the choice.

  • kijonrwslows

    not saying that him and i need not think the severity of your challenge along with the pain it will be causing.It is critical to feel the emotion that’s surfaced as a way to accept task and what it means to u .s ..Give you time, on the web .put against your obstacle shoes, do what you want to do about the item, do all to do and when which is done without more may be accomplished at this time, let that go in addition to trust that not saying that him and i need not think the severity of your challenge along with the pain it will be causing.It is critical to feel the emotion that’s surfaced as a way to accept task and what it means to u .s ..Give you time, on the web .put against your obstacle shoes, do what you want to do about the item, do all to do and when which is done without more may be accomplished at this time, let that go in addition to trust that it can be taken care and attention.Wait and grow patient for any right time and after that take another step of progress.Do not necessarily expect that each one challenges is often solved automatically.Some will need time in addition to there always definitely seems to be a cause for this.When difficulties arise really do not think you will be being designated and disciplined.Challenges could be the stuff life is manufactured out of.However, how you choosed to overcome task will establish your rate of good results.In the text of Symbol Victor Hansen, Dont put it off until everything is exactly right.It may never often be perfect.There are normally challenges, obstacles and poor conditions.Alright, so what!.Get going now.With the help of each measure you acquire, you is going to grow more robust and tougher, more and many more skilled, increasingly successful..

  • t have fantastic discount offers for his or her customers.Many of these websites additionally offer membership in case you travel lots and would wish to hear about the latest promotions and cut price packages.These sites plus the people just who run these are often known as online consolidators and you may contact these products anytime in order to ask queries and learn about the best and newest trends with airfares.
    Once you’ve short-listed a number of sites, the next matter to do is usually to observe them a couple of days to determine what spot locations are the best ones to get discount airfares and consider some of the days for airfares proceed down.You may notice a typical pattern in the good and the bad of airfares.Note that down to see when typically the tickets could be the cheapest for just a particular location.
    Exactly like certain a short time are cheaper than other people, some seasons may also be cheaper than others.Remember thatt have fantastic discount offers for his or her customers.Many of these websites additionally offer membership in case you travel lots and would wish to hear about the latest promotions and cut price packages.These sites plus the people just who run these are often known as online consolidators and you may contact these products anytime in order to ask queries and learn about the best and newest trends with airfares.

    Once you’ve short-listed a number of sites, the next matter to do is usually to observe them a couple of days to determine what spot locations are the best ones to get discount airfares and consider some of the days for airfares proceed down.You may notice a typical pattern in the good and the bad of airfares.Note that down to see when typically the tickets could be the cheapest for just a particular location.

    Exactly like certain a short time are cheaper than other people, some seasons may also be cheaper than others.Remember that in case you are planning to waste this Christmas somewhere else, then booking for the flight way earlier would be the ultimate way to go.It is strongly recommended that people book not less than four months prior to a flight.Similarly summer could be the peak period when people opt for vacations scattered cooler than their city.Now of 12 months is additionally expensive for the purpose of air drivers.But needless to say there are consolidators that will book you upfront for any cheaper air travel.

    Last-minute deals may also be of particular desire for this class.Many websites will provide you with information around the last-minute savings that certain airlines have to offer to sell off off his or her’s extra seats.But most of these deals are certainly not available for everyone destinations.You will need to either bide time until your location to be listed on one of them offers or acquire some various option.Although last-minute reservation should come very cheap often (even 70% discount emerges by certain airlines), but there’re useful only should you be traveling on your own or you have lots of time on your hands.

    Early-morning airfares are generally cheaper compared to the rest.In the same way, flying over a Friday and ever coming back on Tuesday morning happen to be cheaper compared to flying for a Saturday and re-occurring on Weekend evening.You will need to plan your own trip so and come up with some changes to adjust to this kind of schedule, but not surprisingly it could save you significant amounts of money since weekend airfares are now and again sky-high, particularly if the position is favorite.

    They’re only limited strategies to finding low cost airfare online.Once you are actually there you will see out significant amounts of information all by yourself.So usually do not waste time, just log online and inevitably be an airliner that games your schedule plus your budget.

  • imiltsiass

    in, spooky morning, snap-apple nighttime, costume day/da de los disfrazes, along with pooky overnight, Halloween is actually popular in numerous western international locations, including the us, ireland, scotland, wales, great britain, canada, often australia as well as new zealand.In recent years, glow stands & directed glow products are getting to be very well known during Halloween parties celebrations.Young children use Halloween night glow stays and brought about glow programs during day celebrations.in, spooky morning, snap-apple nighttime, costume day/da de los disfrazes, along with pooky overnight, Halloween is actually popular in numerous western international locations, including the us, ireland, scotland, wales, great britain, canada, often australia as well as new zealand.In recent years, glow stands & directed glow products are getting to be very well known during Halloween parties celebrations.Young children use Halloween night glow stays and brought about glow programs during day celebrations.The terrifying glow at nighttime Halloween sparkle products assistance kids a great deal out on trick as well as treating after dark and currently have great excitement.Halloween shine products usually are not just for the purpose of fun together with scaring rather and also they keep young ones safe along with visible once they are outside in dreary.Halloween gleam sticks, brought about flash stays, glow jewelry, glow wristbands, glow headwears or anything else, make any occasion delightful.The thing about these kind of glow programs is that they can be extremely reliable and low-priced.You enables your little ones to play just read the simple products without the need of worrying around anything.You can get these shine products inside bulk on-line.These products can be bought in bulk on-line.You may also get affordable glow services and inexpensive glow products and services online.If you would like some high-quality glow solutions online, visit this glow house that promises lots of quality sparkle products.

  • fakehandbags

    here will be restrictions to the amount and variety of wedding decorations which they can display and you will need to know this unique beforehand.Sometimes there may also be restrictions in noise all this is something verify, customer know when your policies.If you know what the polices are but like the big event venue it really is fairly effortless adapt a decorations and even wedding prefer to fit your venue and its particular restrictions.However you prefer to know thihere will be restrictions to the amount and variety of wedding decorations which they can display and you will need to know this unique beforehand.Sometimes there may also be restrictions in noise all this is something verify, customer know when your policies.If you know what the polices are but like the big event venue it really is fairly effortless adapt a decorations and even wedding prefer to fit your venue and its particular restrictions.However you prefer to know this give you and not final so it may be very useful to ask premature.

    Parking
    This is certainly something considering when you look at the venue.Maybe there is enough storing space for everybody who will be attending your wedding day.Expecting friends and family to park far off and walk can definitely be quite a lot to consult.You want the presentation to become as easy as is feasible and a good amount of parking can help your friends and family feel welcomed.This is especially those friends and family that turn up fashionable late into the event.

    On potential marriage ceremony venue sites before hand you may learn plenty and consequently make the decision determined by your collected information.The most essential concern is how to feel regarding the site.Again have faith in your instinct in that arena and make certain the web page is a factor that speaks you.It have to be a lace that you could easily think about yourself having a wedding at.

  • imiltsiass

    asy to get into Victoria Key or JC Pennys as well as spend on a thousand dollars for a few items should you not prioritize and even set a good limit.
    The easiest perhaps the process that will narrow decrease your selection by far the most is obtaining your volume.Although labels and which kind of womens apparel you would like can vary bigger, generally any size remains exactly the same for many products.Then when you go to a retail store, it either has an individual’s size or very easy.If very easy, you are able to either await it to come in any size, check out a different retail store or select a diffeasy to get into Victoria Key or JC Pennys as well as spend on a thousand dollars for a few items should you not prioritize and even set a good limit.

    The easiest perhaps the process that will narrow decrease your selection by far the most is obtaining your volume.Although labels and which kind of womens apparel you would like can vary bigger, generally any size remains exactly the same for many products.Then when you go to a retail store, it either has an individual’s size or very easy.If very easy, you are able to either await it to come in any size, check out a different retail store or select a different thing.

    Another phase containing made option just inside the past couple of decades is without a doubt Internet purchasing.With the web continuously expanding and more stores opening an via the internet shopping internet site, it has become increasing popular to shop online.If you shop online, you contain a much bigger selection to select from and a great endless variety of stores to choose from.There would be the downsides and even risks of having the unsuitable item sent, having to cover shipping and having to wait in your item to always be shipped.On the other hand, it opens the door to a much bigger selection in womens apparel than previously.

    With pretty much everything said, it is right now your decision to settle on what brand you like most as well as what style you would like.Whether you desire basketball and / or tennis women active wear is really a decision to make.Do you want a black or simply brown and white ladies business agree with? Are you looking for a comfortable nightgown and also sexy females intimate nighties? These are all questions you’ll need to ask by yourself when seeking out womens clothes, but typically the sky is the limit intended for what the stores have to offer you.

You must be logged in to post a comment.