Search

Admin

2.1 — Basic addressing and variable definition

Addressing memory

This lesson builds directly on the material in the section “1.3 -- 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 programs to use. When a variable is defined, 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 random segment of memory, all you would see is …011010100101010… or some combination thereof. Memory is organized into sequential units called addresses. Similar to how a street address can be used to find a given house on a street, the memory address allows us to find and access the contents of memory at a particular location. Perhaps surprisingly, in modern computers, each bit does not get its 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 its “type”.

Fundamental data types

C++ comes with built-in support for certain data types. These are called fundamental data types (in the C++ specification), but are often informally called basic types, primitive types, or built-in types.

Here is a list of the fundamental data types, some of which you have already seen:

Category Types Meaning Example Notes
boolean bool true or false true
character char, wchar_t, char16_t, char32_t a single ASCII character ‘c’ char16_t, char32_t are C++11 only
floating point float, double, long double a number with a decimal 3.14159
integer short, int, long, long long a whole number 64 long long is C99/C++11 only
void no type void n/a

This chapter is dedicated to exploring these basic data types in detail.

Defining a variable

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

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

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

Variable initialization and assignment

When a variable is defined, you can immediately give that variable a value. This is called initialization.

When we assign values to a defined variable using the assignment operator (equals sign), it’s called an explicit initialization:

When a variable is defined, you can also assign a value using an implicit initialization:

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

When a variable is given a value after it has been defined, it is called an assignment.

C++ does not provide any built-in way to do an implicit assignment.

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:

You can also assign them values on the definition line:

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

The first mistake is giving each variable a type when defining variables in sequence. This is not a bad mistake because the compiler will complain and ask you to fix it.

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

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

In the top statement, the nValue1 variable will be left uninitialized, and the compiler may or may not complain. If it doesn’t, 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 to consider the case of implicit initialization:

This makes it seem a little more clear that the value 5 is only being assigned to nValue2. This is one good reason to favor implicit initialization over explicit initialization. Implicit initialization can also perform better in some cases.

Rule: Use implicit initialization instead of explicit initialization

Where to define variables

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

This style is now obsolete. C++ compilers do not require all variables to be defined at the top of a function. The proper C++ style is to define variables as close to the first use of that variable as possible:

This has quite a few advantages.

First, variables that are defined only when needed are given context by the statements around them. If x were defined 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. Defining x amongst a bunch of input/output statements helps make it obvious that this variable is being used for input and/or output.

Second, defining 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 define and then immediately initialize it with the value we want it to have.

Rule: Define variables where they are needed.

2.2 -- Void
Index
1.11 -- Chapter 1 comprehensive quiz

53 comments to 2.1 — Basic addressing and variable definition

  • Abhishek

    That was easy 😀

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

        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.

        • Alex

          As noted in the lesson, declaring variables as close to the first use as possible is a widely accepted C++ convention. Whether you choose to follow convention is up to you.

          Companies that follow the “declare at the top” convention likely have roots in older C code, where that style of definition was a necessity, and haven’t updated their style guidelines in favor of modern best practices.

          I also would not recommend using the “pv” or “lv” prefix unless you like typing more than necessary. Variables should be assumed to be locally scoped unless otherwise indicated.

        • DR

          I wouldn’t go further than m_ when flagging variables in this day and age; Hungarian notation is a huge thing of the past and is discredited by Microsoft themselves.

          Why would you declare a variable that takes up memory if it might not be used…or if you leave it non-initialized what would be the use of "opening a back door" to something that could lead to a potential edge case bug.

  • CuView

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

    • When x is defined in your example, 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:

      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?

    • As far as I know, when it comes to built-in data types, there’s no substantive difference. I ran some timing tests on each and they performed identically in my test cases.
      For user-defined classes (something we’ll cover later), implicit initialization performs better, as it avoids making an unnecessary copy of the class.

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

    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.

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

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

    • Alex

      Good question. The compiler creates something called a symbol table, to keep track of details like a variable’s name, type, scope, etc… The linker also has a symbol table to keep track of exported functions and variables so they can be properly linked. Symbol tables are complicated, and you probably won’t need to know the details of how they work unless you’re writing a parser or compiler.

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

    • Alex

      I’d counter with a few points:
      1) Global variables should be used exceedingly rarely.
      2) If global variables are used, they can be easily identified if you label them with a specific prefix (e.g. g_).
      3) If your function is 300 lines, it probably should be refactored into smaller functions. I rarely write a function that is more than 100 lines, and most of the time they are less than 50.

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

    • Alex

      When you say you were taught to declare variables “in the header files under the private section”, it sounds like you’re actually talking about how to write a class declaration. The rules for where class member variables and functions are defined are a little different (and covered in a future chapter).

      In this lesson, we’re talking about function parameters and local variables.

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

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

    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.

    • rameye

      It was a quiz exercise on functions. Not a one-liner contest :)

      • Alex

        Yes, the chapter 1 comprehensive quiz has you go through extra steps for the purpose of ensuring you understand some basic concepts that will be used later. It’s a little extraneous, as you’ve noticed, but the understanding will serve you well in the future.

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

    • yes, ‘wrote’ is indeed the past tense for ‘write’.
      Anyway, I guess it depends on the compiler, because mine will pop up a warning in either case. I suppose VS05 did stuff differently.

      • Kostas81

        Thank you zingmars once again for your answer! (and for the little grammar help … :) )

      • Alex

        I’ve found that Visual Studio is capable of showing uninitialized variable warnings for simple cases, but may or may not for slightly more complicated cases.

        For example, Visual Studio 2013 gives an unassigned variable compiler error for this code:

        But NOT for this code:

  • M Harran

    Alex, I’m coming late to the party but you should take pride that your tutorial is still proving useful to people 6 years down the road :)

    I’m coming from a C# background so I’m well used to the idea of employing something like

    Reading around places like stackoverflow, however, a lot of programmers say this is a bad idea, that you should specifically state the parts of the library that you are using i.e.

    Their argument is that by using the whole namespace, you may cause a conflict between a function in some other file that you are including which happens to have the same name as something in the standard library.

    Any comment on that argument?

    Thanks for a brilliant tutorial by the way, coming from C# and Visual Studio, it is perfect for me.

    • Alex

      Sure. The folks at Stack Overflow are correct -- the looser you are with your using statements, the more likely a naming conflict becomes. Explicitly including the classes you want from the library (e.g. using std::cin) is safer than including the whole library (using namespace std;). If you’re really concerned about naming conflicts, you can even go one step further and avoid “using” statements altogether and explicitly qualify everything. e.g.

      Generally, I’ve found that as long as your using statements are declared within functions (and not done at the global scope) the potential for conflicts is fairly minimal.

  • PrimalKyogreOVER9000!!!!

    Great tutorial Alex! Really enjoying so far.

    Can you please explain what bool, char, float and double variable types mean? And what are they used for?

    Thanks

  • Woopsie

    Third paragraph, second-to-last sentence, “it’s” should be “its”

    Also, last sentence before “Declaring a variable”, another it’s/its

  • Adam

    Alex,

    My background is in mechanical engineering. I've some experience with Python, MATLAB, and some Visual Basic in high school. I am telling you that as I believe my question stems from the experience I've had writing code for these applications as opposed to commercial software.

    In engineering and math it is often helpful to declare certain variables at the top. For instance a value for friction that is used in many equations and places throughout the code. The value can then be easily found and changed. This is not only easier but prevents mistakes by eliminating the need to find each use of the variable and change it locally.

    Is this a case where using an upfront declaration is appropriate? If not how would you handle a situation like this?

  • Chance Meser

    My code is saying:

    ‘main.exe': Loaded ‘C:\Users\Chance\Documents\Visual Studio 2010\Projects\main\Debug\main.exe’, Symbols loaded.
    ‘main.exe': Loaded ‘C:\Windows\SysWOW64\ntdll.dll’, Cannot find or open the PDB file
    ‘main.exe': Loaded ‘C:\Windows\SysWOW64\kernel32.dll’, Cannot find or open the PDB file
    ‘main.exe': Loaded ‘C:\Windows\SysWOW64\KernelBase.dll’, Cannot find or open the PDB file
    ‘main.exe': Loaded ‘C:\Program Files (x86)\Norton 360\NortonData\21.6.0.32\Definitions\BASHDefs\20150309.001\UMEngx86.dll’, Cannot find or open the PDB file
    ‘main.exe': Loaded ‘C:\Windows\SysWOW64\msvcp100d.dll’, Symbols loaded.
    ‘main.exe': Loaded ‘C:\Windows\SysWOW64\msvcr100d.dll’, Symbols loaded.
    The thread ‘Win32 Thread’ (0xa24) has exited with code 0 (0x0).
    The program ‘[3856] main.exe: Native’ has exited with code 0 (0x0).

  • Win

    How does memory know what  type is stored there in memory. I mean how does it identify that this byte is type of int, and maybe another byte is type of char ,etc. Is there any value that tell the memory what type of this byte is.

    I’m sorry for my bad English. I hope you can understand what I mean.

    Thank you.

    • Alex

      Memory doesn’t know what type of data is stored in it. It’s just dumb storage.

      All variables have an associated address that gets assigned to the variable, either by the compiler at compile time or by the OS at runtime.

      The program also keeps a separate table of meta-information (called a symbol table) that includes things like the variable’s name, type, size, and scope.

      Between the address and the symbol table, the program has everything it needs to read/write values of a particular data type into memory.

  • Pankaj kushwaha

    Hi Alex ,
    you can also mention that :

    int i = 7.5 ;
    pass the compilation (with loss of data) , while
    int i(7.5)
    gives compilation error , so its safe to use second one.

  • Todd

    Typos.

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

    "Implicit initialization can also be more performant (can also perform better) in some cases." (oddly enough, ‘performant’ is a noun, not an adjective)

Leave a Comment

  

  

  

11 + twenty =

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