4.1 — Introduction to fundamental data types

Bits, bytes, and memory addressing

In lesson 1.3 -- Introduction to 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 (also called a 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 memory addresses (or addresses for short). 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 computer architectures, each bit does not get its own unique memory address. This is because the number of memory addresses are limited, and the need to access data bit-by-bit is rare. Instead, each memory address holds 1 byte of data. A byte is a group of bits that are operated on as a unit. The modern standard is that a byte is comprised of 8 sequential bits.

Key insight

In C++, we typically work with “byte-sized” chunks of data.

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

Memory Addressing

As an aside...

Some older or non-standard machines may have bytes of a different size (from 1 to 48 bits) -- however, we generally need not worry about these, as the modern de-facto standard is that a byte is 8 bits. For these tutorials, we’ll assume a byte is 8 bits.

Data types

Because all data on a computer is just a sequence of bits, we use a data type (often called a “type” for short) to tell the compiler 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 compiler “the piece of memory that this variable uses is going to be interpreted as an integer value”.

When you give an object a value, the compiler and CPU take care of encoding your value into the appropriate sequence of bits for that data type, which are then stored in memory (remember: memory can only store bits). For example, if you assign an integer object the value 65, that value is converted to the sequence of bits 0100 0001 and stored in the memory assigned to the object.

Conversely, when the object is evaluated to produce a value, that sequence of bits is reconstituted back into the original value. Meaning that 0100 0001 is converted back into the value 65.

Fortunately, the compiler and CPU do all the hard work here, so you generally don’t need to worry about how values gets converted into bit sequences and back.

All you need to do is pick a data type for your object that best matches your desired use.

Fundamental data types

C++ comes with built-in support for many different data types. These are called fundamental data types, 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:

Types Category Meaning Example
long double
Floating Point a number with a fractional part 3.14159
bool Integral (Boolean) true or false true
char8_t (C++20)
char16_t (C++11)
char32_t (C++11)
Integral (Character) a single character of text ‘c’
long long (C++11)
Integral (Integer) positive and negative whole numbers, including 0 64
std::nullptr_t (C++11) Null Pointer a null pointer nullptr
void Void no type n/a

This chapter is dedicated to exploring these fundamental data types in detail (except std::nullptr_t, which we’ll discuss when we talk about pointers). C++ also supports a number of other more complex types, called compound types. We’ll explore compound types in a future chapter.

Author's note

The terms “integer” and “integral” are similar, but have different meanings. Integers are a specific data type that hold positive and negative whole numbers, including 0. The term “integral types” (which means “like an integer”) includes all of the boolean, characters, and integer types (and thus is a bit broader in definition). Integral types are named so because they are stored in memory as integers, even though they behave slightly differently.

The _t suffix

Many of the types defined in newer versions of C++ (e.g. std::nullptr_t) use a _t suffix. This suffix means “type”, and it’s a common nomenclature applied to modern types.

If you see something with a _t suffix, it’s probably a type. But many types don’t have a _t suffix, so this isn’t consistently applied.

4.2 -- Void
3.x -- Chapter 3 summary and quiz

233 comments to 4.1 — Introduction to fundamental data types

  • Thomas Keith

    I have run into some coders that have declared their variables at the top of their (.vbs) code.  I always found it difficult to troubleshoot the script when it was necessary.  Does anyone know why the "declare at top" protocol was initiated in the first place?  I totally agree with "declare & initialize when used."  That's my M.O.

    • Alex

      Some (mostly older) languages used to require all variables to be declared at the top of the file or function. C used to be like this until C99.

      Modern best practices are to declare variables as close to their first use as possible. However, some older programmers have habits that die hard.

  • List initialization is the safest way to initialize a variable. It gives a warning when narrowing conversion occurs in Code::Blocks (C++ 11) and throws an error in updated(or other) compilers/IDE's.

    All the readers can have a look at this Online Compiled Code

  • Jim

    In this lesson I believe you introduced variable names with a prefix, like int nValue & bool bValue,for the first time.  But you failed to tell users why you used them. I believe this is a good programming practice and I think you should mention why.

    I'm wonder why you mentioned the following rule:

    "Rule: Use implicit initialization instead of explicit initialization"

    I've shown both below... I prefer the explicit because it's easy to see that an assignment was made. Do you have a specific reason for this?

    One last thing you mentioned, "C++ does not provide any built-in way to do an implicit assignment."

    So you can implicit initialize int nValue(5). This does not make any sense to me, when in fact it has already been assigned (5)?

    • Alex

      Funny you should post this, as I was just in the process of revising the lesson. It's updated now, have a re-read.

      1) Prefixing variables names with a letter indicating the type is called Hungarian Notation. This tutorial used to recommend it, but the best and brightest minds in the field have fairly unanimously concluded that it doesn't provide enough value to be worthwhile, especially as compilers have gotten smarter and the language has gotten better (with C++11). I've been in the process of stripping it out of the tutorials as I rewrite them, but I missed a couple of instances here.

      2) Regarding implicit initialization, an assignment was NOT made -- an initialization was! The two seem similar (and achieve similar ends in this case) but are in fact distinct. It's worth understanding the difference now, as it becomes more relevant later.

      The primary reason I recommend implicit over explicit initialization is that classes (which are a user-defined type that is at the heart of C++) cannot be initialized using explicit initialization. So you might as well get used to implicit initialization now, cause you're going to have to use it a lot later.

      3) Again, make sure you understand the difference between initialization and assignment. You can implicitly initialize something, but C++ does not provide a way to implicitly assign a value (e.g. if you try value(5), it will think you're trying to make a function call, not do an implicit assignment).

  • Avneet

    Alex, you can write about the safest way to initialize objects that is via the initializer list (I don't know why the great stroustrup said it an initializer list while we can put in a single value). Compiler throws error when data lose is possible.

    int value {7.5} // compile error

  • Todd


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

      • C++ newbie

        Your comment in line 5 stretches out too far so that it goes on to the next line.  You should insert // before "ble" in possible, or just close that line in /* */

      • James Smith

        Actually, performant is an adjective. It means "functioning well or as expected". At least that's what Oxford Dictionary says.
        Like C++, programmers overload words. I was shocked to find out that even the word physical got overloaded :) Imagine that! You can talk about the physical structure of a program, as opposed to its logical structure.

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

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

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

  • Adam


    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?

  • Woopsie

    Third paragraph, second-to-last sentence, "it's" should be "its"

    Also, last sentence before "Declaring a variable", another it's/its

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


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

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

  • prafull.badyal

    gud..thanks to sir alex

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

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

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

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

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

  • Tate

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

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

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

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

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

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

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

  • Abhishek

    That was easy :D

Leave a Comment

Put all code inside code tags: [code]your code here[/code]