An integer is an integral type that can represent positive and negative whole numbers, including 0 (e.g. -2, -1, 0, 1, 2). C++ has *4* different fundamental integer types available for use:

Type | Minimum Size | Note |
---|---|---|

short | 2 bytes | |

int | 2 bytes | Typically 4 bytes on modern architectures |

long | 4 bytes | |

long long | 8 bytes | C99/C++11 type |

The key difference between the various integer types is that they have varying sizes -- the larger integers can hold bigger numbers.

A reminder

C++ only guarantees that integers will have a certain minimum size, not that they will have a specific size. See lesson 4.3 -- Object sizes and the sizeof operator for information on how to determine how large each type is on your machine.

Signed integers

When writing negative numbers in everyday life, we use a negative sign. For example, *-3* means “negative 3”. We’d also typically recognize *+3* as “positive 3” (though common convention dictates that we typically omit plus prefixes). This attribute of being positive, negative, or zero is called the number’s sign.

By default, integers are signed, which means the number’s sign is preserved. Therefore, a signed integer can hold both positive and negative numbers (and 0).

In this lesson, we’ll focus on signed integers. We’ll discuss unsigned integers (which can only hold non-negative numbers) in the next lesson.

Defining signed integers

Here is the preferred way to define the four types of signed integers:

1 2 3 4 |
short s; int i; long l; long long ll; |

All of the integers (except int) can take an optional *int* suffix:

1 2 3 |
short int si; long int li; long long int lli; |

This suffix should not be used. In addition to being more typing, adding the *int* suffix makes the type harder to distinguish from variables of type *int*. This can lead to mistakes if the short or long modifier is inadvertently missed.

The integer types can also take an optional *signed* keyword, which by convention is typically placed before the type name:

1 2 3 4 |
signed short ss; signed int si; signed long sl; signed long long sll; |

However, this keyword should not be used, as it is redundant, since integers are signed by default.

Best practice

Prefer the shorthand types that do not use the *int* suffix or signed prefix.

Signed integer ranges

As you learned in the last section, a variable with *n* bits can hold 2^{n} different values. But which specific values? We call the set of specific values that a data type can hold its range. The range of an integer variable is determined by two factors: its size (in bits), and whether it is signed or not.

By definition, a 1-byte signed integer has a range of -128 to 127. This means a signed integer can store any integer value between -128 and 127 (inclusive) safely.

As an aside...

Math time: a 1-byte integer contains 8 bits. 2^{8} is 256, so a 1-byte integer can hold 256 different values. There are 256 different values between -128 to 127, inclusive.

Here’s a table containing the range of signed integers of different sizes:

Size/Type | Range |
---|---|

1 byte signed | -128 to 127 |

2 byte signed | -32,768 to 32,767 |

4 byte signed | -2,147,483,648 to 2,147,483,647 |

8 byte signed | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |

For the math inclined, an n-bit signed variable has a range of -(2^{n-1}) to 2^{n-1}-1.

For the non-math inclined… use the table. :)

Integer overflow

What happens if we try to assign the value *280* to a 1-byte signed integer? This number is outside the range that a 1-byte signed integer can hold. The number 280 requires 9 bits (plus 1 sign bit) to be represented, but we only have 7 bits (plus 1 sign bit) available in a 1-byte signed integer.

Integer overflow (often called *overflow* for short) occurs when we try to store a value that is outside the range of the type. Essentially, the number we are trying to store requires more bits to represent than the object has available. In such a case, data is lost because the object doesn’t have enough memory to store everything.

In the case of signed integers, which bits are lost is not well defined, thus signed integer overflow leads to undefined behavior.

Warning

Signed integer overflow will result in undefined behavior.

In general, overflow results in information being lost, which is almost never desirable. If there is *any* suspicion that an object might need to store a value that falls outside its range, use a type with a bigger range!

Integer division

When dividing two integers, C++ works like you’d expect when the quotient is a whole number:

1 2 3 4 5 6 7 |
#include <iostream> int main() { std::cout << 20 / 4; return 0; } |

This produces the expected result:

5

But let’s look at what happens when integer division causes a fractional result:

1 2 3 4 5 6 7 |
#include <iostream> int main() { std::cout << 8 / 5; return 0; } |

This produces a possibly unexpected result:

1

When doing division with two integers (called integer division), C++ always produces an integer result. Since integers can’t hold fractional values, any fractional portion is simply dropped (not rounded!).

Taking a closer look at the above example, 8 / 5 produces the value 1.6. The fractional part (0.6) is dropped, and the result of 1 remains.

Similarly, -8 / 5 results in the value -1.

Warning

Be careful when using integer division, as you will lose any fractional parts of the quotient. However, if it’s what you want, integer division is safe to use, as the results are predictable.

4.5 -- Unsigned integers, and why to avoid them |

Index |

4.3 -- Object sizes and the sizeof operator |

What happens when you try to compile a program if you declare the iostream header file before #include "stdafx.h"

- When running a program with erros (more errors are generated running when the iostream header file is included first)

- Is there any particular reason for this

If you're using visual studio and precompiled headers are turned on (which they are by default), the compiler will error. This is because visual studio requires #include "stdafx.h" to be the first line of a code file when precompiled headers are turned on. You can either comply with that restriction, or turn precompiled headers off.

I don't understand. what's the importance of this lesson ??

Is this even used a lot? 'cause it doesn't really look like it does ?

Integers are used everywhere in C++. This lesson talks about the different kinds of integers, and some of the things you need to watch out for (e.g. overflow).

Alex, you made an error on your website "In addition to being *less* typing, adding the prefix int makes the type harder to distinguish from variables of type int. This can lead to mistakes if the short or long modifier is inadvertently missed."

How to use long integer, can you explain me by the one example

Hi Sachin!

Alex, can you explain the error happen.

#include <stdio.h>

void main() {

int u;

unsigned int v; // short 型変数u と、unsigned short 型変数v を宣言する

u = 2147483647; // short 型変数の最大値をu に代入

v = 4294967295; // unsigned short 型変数の最大値をv に代入

printf("INT_MAX = %d \n", u);

printf("UINT_MAX = %u \n", v);

u = u + 1;

v = v + 1;

printf("INT_MAX + 1= %d \n", u);

printf("UINT_MAX + 1 = %u \n", v);

u = u - 1;

v = v - 1;

printf("INT_MAX + 1 - 1 = %d \n", u);

printf("UINT_MAX + 1 - 1 = %u \n", v);

}

Hi mad!

The compiler is pretty clear about this:

"error: ‘::main’ must return ‘int’"

thank you mr nascardriver. one more thing, why when the max value of int and unsigned int were add by 1 they return to minimum value?

Let's look at a 4 bit binary number

If we add 1 we get

All bits get set to 0 and the first bit turns into a 1.

What if that first bit wasn't there, because you've already used all bits?

This is what should happen, but we're limited to 4 bits (In this example), so the most significant bit disappears and we're left with 0.

References

* https://en.wikipedia.org/wiki/Integer_overflow

ohh.. so in this case it called interger overflow?

Correct, because the resulting number overflows into bits that aren't part of the variable.

ohh orait. thank you mr nascardriver...

Ah, the overflow issue reminds me of this glitch from the original Civilization game. Ghandi's aggression rating starts at 1, and researching democracy reduces aggression by 2... lo and behold, nuclear armed Ghandi with 255 aggression in the late game. Normally, leaders are given a rating from 1 to 10, but I guess they had an unsigned integer there.

https://kotaku.com/why-gandhi-is-such-an-asshole-in-civilization-1653818245

Yes, this is a great example of a famous overflow glitch! And one that wouldn't have happened if they'd used a signed integer instead of an unsigned char!

Thanks for bringing this up, undoubtedly other readers will find this interesting.

As an other reader, I confirm I found this interesting :)

how can a char be signed?

Hi Anushka!

A char is an 8bit integer. Your compiler/console just know how to read/display it as a character.

excuse me mr nascardriver sir but um what does this have to do with bernie sanders?

Bernie Sanders is an AI written in c++

"Note that C++ only guarantees that integers will have a certain minimum size, not that they will have a specific size."

Does it mean that on some architecture the int data type can have a size of 4 bytes, but on some other architecture it can have a size of 8 bytes? If the answer is true, does it affect the range of int (on the architecture with 4-byte sized int a range of -2,147,483,648 to 2,147,483,647 and on the architecture with 8-byte sized int a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.) Thanks!

Yes, though most often an int will be 2 or 4 bytes. I'm not aware of any architectures that have an int size of 8 bytes, but that doesn't meant there aren't or won't ever be.

Thank you! I'm still wondering if it does affect the range. I don't think the maximum value of an 4-byte sized int can fit in a 2-byte sized int. Basically, a 2-byte sized one is the same thing as the short data type. Right?

Hi Cosmin!

The maximum of a 4-byte sized integral date type cannot fit in a 2-byte sized one. If that was the case there wouldn't be a need for anything bigger than 2 bytes.

Here are the sizes and maximum values of some common integral data types:

Produced by

Compiled with gcc version 7.1.1 20170622 (Red Hat 7.1.1-3) (GCC)

Thank you, nascardriver!

Hello sir,

while i was executing this programming, i was getting first 255 interger number output like 65 -

"A" .....97- "a" ..... 256 "smily" ..etc + my program continuously executing countless time with computer warning sound "beep"

what is the problem in this program?

#include<iostream>

int main()

{

unsigned char c ;

for(c=0; c<256; c++)

{

std::cout << c << std::endl;

}

return 0;

}

When you print a char using std::cout it prints as the ASCII value with that code. So your program is printing all of the ASCII code points from 0 to 255. However, not all ASCII code points are printable, and the ones above 127 aren't well defined. If you try to print these, the results are indeterminate. In your case, one of those unprintable characters is translated by your console as a beep. The smiley is your console's font showing a smiley for one of the characters (probably one of the ones above 127).

Dear Alex,

Quick (and perhaps stupidly obsessive) question: Is overflow the same (or does it at least work the same) as "narrowing"?

I started this question on StackOverflow, but as usual, it was met with dubious ire: https://stackoverflow.com/questions/44895350/why-would-an-overflow-on-an-object-of-built-in-type-cause-an-exception-undefined

I would also assume that overflow occurs on all the arithmetic types, since it is usually referred to as either "arithmetic overflow" or "arithmetic underflow," but is that even true?

Thank you Alex for your help, I'm 13 and I learned a course on Openclassrooms but the course was obsolete, I looked for a book in the web I saw C++ Primer and few time after I saw your site Learncpp.com. Since I had these two ressources, I don't lose the time. I have to say that you did the layoutfor the homepage very attracting. I'm very happy for reaching a site like this and a book like C++ primer which is a good ressource too. I moving very well. God Bless you, you deserve it.

McSteven

IN THE LAST SAMPLE PROGRAM:

FIRST

WHO'S THERE TO TELL THE COMPILER TO PRODUCE AN INTEGER RESULT?

SECOND

WILL BOTH THE INTEGERS NOT BE TYPECASTED TO FLOAT BY THE COMPILER ITSELF TO PRODUCE A FLOAT RESULT?

The compiler produces an integer result if both of the operands are integers, which they are in this case. They will not be typecast to a float. If either or both of the operands are float, then you'll get a float result.

In future lessons we talk more about how type conversions happen and more about how operators work, which should help make this clearer.

Hi Alex, I want to say I'm enjoying the site and the C++ lessons are outstanding. I just have 1 concern for this topic about integers. That being, I really don't understand the purpose of these integers and their limits. Like char, short, long, and long long I dont understand why they would be used in a code and why having a limit to their size would be about. Keep in mind I'm a beginner with absolutely no experience, just the lessons following up to this one.

Integers are used when you want to store whole numbers (e.g. 1, 2, 3). For example, someone's age in years, or the number of times something has occurred. The types (char, short, int, long, etc...) determine how large of an integer that type can store.

Here's a sample program where we use an integer to store an age:

What else can I help clarify for you?

That helps me all I needed, thanks a lot.

I was curious to know how the example with unsigned short x = 0; x = x -1 got the result of 65335, but I was able to work out why using the complement method as detailed on this page here: http://www.wikihow.com/Subtract-Binary-Numbers.

You can get the same result by initializing an unsigned short to -1.

I talk more about binary representation and twos complement in chapter 3.

OK, great, thanks!

how to find the absolute difference between 2 integers?

is there any built in function for it?

Yes, you can use the abs() function that lives in the cstdlib header.

Hi Alex,

I played with numbers after going through this part and noticed an odd thing. If I use the code below, and add a decimal number to X, like say, 0.5. The program goes wild and starts spamming "Add to X: X is -1". What happens here and why does it completely break the program like that?

It has to do with how cin and operator>> process input. If you type 0.5, the 0 gets extracted to x, but the '.' gets left in the input stream. Next iteration, it tries to extract the '.', which fails because character '.' can't be extracted to an integer. This causes cin to go into failure mode. I talk about this in more detail in lesson 5.10, if you want to read ahead.

hey guys i have a small problem.why does this program give no value?Is it because the +1 is out of the range and one gets and over flow of the bit.

Here is the program.

numeric limits<int>::max()+1

That's not a program, it's an expression. If it's giving no value, it may be because you're not sending the result of the expression to std::cout?

Hi Alex,

#include <iostream>

using namespace std;

int main ()

{

unsigned int a = -7;

int b = 2;

int result;

result = a - b;

cout << result;

return 0;

}

==========================================

An unsigned integer is one that can only hold positive values.

When I assigned "-7" to "unsigned int a", I expected something wrong in the output but it works! The output is -9.

Could you please let me know why?

Thanks, Have a great day.

This one is a little challenging to explain -- it has to do with the way signed and unsigned numbers are stored in binary, and the way they are interpreted based on whether the variables are signed or unsigned. Try this:

You'll see that it prints 4294967289. So even though you assigned -7, it stored that huge number. However, if you cast that huge number back to a signed number, you'll see it prints 7:

Essentially, -7 and 4294967289 are stored as the same number in binary -- the difference is in how they are interpreted based on type. Because your result variable is signed, your result is being interpreted as a signed number (-9) instead of a large unsigned number (4294967291 I think).

I cover related topics in chapter 3, so if the above seems a bit incomprehensible at this point, keep reading.

Hi Alex,

I’ve finished Chapter 3. Please correct me if I am wrong.

-7 is represented in binary as 1111 1111 1111 1111 1111 1111 1111 1001.

2 is represented in binary as 0000 0000 0000 0000 0000 0000 0000 0010.

When “result = a – b;” statement is executed, something like this happens:

result = 1111 1111 1111 1111 1111 1111 1111 1001 – 0000 0000 0000 0000 0000 0000 0000 0010

result = 1111 1111 1111 1111 1111 1111 1111 0111.

Because result is signed, it is being interpreted as a signed variable that can hold both negative & positive numbers (-9 & 4294967287). Both numbers (-9 & 4294967287) are represented in binary as 1111 1111 1111 1111 1111 1111 1111 0111.

Now I need to know which number (-9 or 4294967287) should be printed.

From what I’ve learned in Chapter 3- *Signed numbers and two’s complement, I am able to tell (-9) should be printed.

*Signed numbers and two’s complement: Signed integers are typically stored using a method known as two’s complement. In two’s complement, the leftmost (most significant) bit is used as the sign bit. A 0 sign bit means the number is positive, and a 1 sign bit means the number is negative.

To convert a two’s complement binary number back into decimal, first look at the sign bit.

If the sign bit is 0, just convert the bits for unsigned numbers (I modified this sentence for my example).

If the sign bit is 1, then we invert the bits, add 1, then convert to decimal, then make that decimal number negative (because the sign bit was originally negative).//

So, looking at “1”111 1111 1111 1111 1111 1111 1111 0111, I can tell the number is negative (a 1 sign bit).

The next steps are to invert the bits, add 1, then convert to decimal, then make that decimal number negative (because the sign bit was originally negative):

-Invert the bits: 0000 0000 0000 0000 0000 0000 0000 1000

-Add 1: 0000 0000 0000 0000 0000 0000 0000 1001

-Covert to decimal: 0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+9+0+0+0 = 9.

-Since the original sign bit (1) was negative, the final value is -9.

Yup!

That said, generally you should just avoid unsigned numbers altogether and not worry about conversions like these. :)

Dear Alex

How can I learn easily the C++?

PLEASE!

I NEED SOME SUGGESTIONS.

Step 1: Open tutorial

Step 2: Read

I don't often read the comments, but I'm glad I did so I could see this gem.

Somewhere in this article, you talk about how a variable integer can be named 32-bits integer instead on long. Is that because, in some machines, long takes 32 bits? What am I not understanding correctly?

On 32-bit systems, long is often 32-bits. On 64-bit systems, long is often 64 bits. So yes, we typically use the number of bits when discussing integers because the names (int, long) can vary in size on different machines/architectures.

Ok... I mixed bytes and bits...

Thank you for your answer you're really helpful. Are you the author of this website?

Yes, I am.

i'm using VS2015

i tried the signed int x = -1; and got an error:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

this happened when i do'nt use "signed" too.

Something else must be going on, because that line is fine.

This should print -1:

There are 10 people in the world who understand binary. Those who do and those who don't.

Better phrasing: There are 10

types ofpeople in this world, those who understand binary and those who don't.Hello and many thanks for putting up such a well written tutorial. It's perfect for people like me who want to start from scratch (or almost).

I seem to have a small problem related to this lesson, and I suspect it's because of the compiler (codeblocks 16.01, archlinux x64). This is my quick test program:

My sizeof(unsigned short)=2, so it should show 65535, yet it shows up -1. I tried then with x{65535} and x+1 , but it outputs 65536. Then I tried x{65536} and, using

(to go outside of codeblocks), it shows the warning:

I am very confused right now. Could you please shed some light?

It's not your compiler. If you do this:

You'll get 65535.

But if you do this:

You get -1. Why? Because 1 is a signed number, whereas x is unsigned. Because you're mixing types, the compiler does an implicit conversion, and x is converted to a signed integer (the rules for this are covered in lesson 4.4). Thus, x - 1 is signed, and so you get -1 instead of 65535.

To get the answer you expect, do this:

This avoids the type conversion.

In general, you should not mix signed and unsigned numbers, because the results are often unexpected.

Thank you for the clarification. And, again, for the whole tutorial, even though I'm only at bitwise operations right now. I have to say that these 3 days (4 this one) since I started reading this, made me realize I *understood*.

char data type doesn't stores any numeric value and signed /unsigned just tells us that whether the data type would have -ve values or not.

then what is the point of char data type being signed or unsigned

Char does store numeric values, and you can do integer math with them. They're just not _typically_ used for that purpose.

can u give me an example code explaining how char can be used to do integer maths. :)

btw alex, i must say that u have got an awesome site (which i rarely say for any site).. so thanx 4 sharing all that stuff.. nd i too know hindi.. so i would be happy to contribute for ur hindi site =D

What is the difference between using:

static_cast<int>(a + b)

and

(int)(a+b)

I get the same output when using both the methods

@static_cast is more restricted in the types in can cast. For int, there is no difference between the two. The second version shouldn't be used in C++. Casts are covered in a later lesson.

Thanks for replying! Sorry I don't understand what you mean by "For int, there is no difference between the two"

If you don't understand it, don't worry, it's covered later. For now, just use the first version.

Great Tutorial,i have read many pdf tutorials but i gave up along the way because i wasn't understanding,i thank God i have found this online, and now am back again with C++. Better understanding May Almighty Allah(God) Bless you Abundantly Great ALEX.

When you will add more hindi chapters....?

My Hindi translator went on hiatus, so I'm not sure. :(

Alex, I've been trying to get this for a long long time... in 2 articles (2.3 and 2.4) you managed to explain it to me in such a simple way. Thank you for your work and thank you for sharing it.

If i get this right, signed short can take values form -256 to 255 (2^8 bits) right ? But

#include "stdafx.h"

#include <iostream>

int main()

{

using namespace std;

short x = 255; // largest 16-bit unsigned value possible

cout << "x was: " <<sizeof (x) << endl;

x = x + 1; // 65536 is out of our range -- we get overflow because x can't hold 17 bits

cout << "x is now: " << x << endl;

return 0;

}

prints 255, 256 normally. What am i missing?

Shorts are normally 2 bytes, so the range of a signed short is usually -32768 to 32767.

Yeeea i just got it... 15 bits used for numbers amd the 16th used for +/-.

Keep up the amazing work. Thanks for replying so quickly.

Hi, I have a question about the last example under "Overflow Examples". A wraparound occurred which gave a result of

x was: 0

x is now: 65535

I understand the wraparound result in the previous example, but not quite sure why this wraparound results in 65535? Trying to understand via the binary, but I can't figure it out. Can anyone help??

Note to Alex: Thanks for this tutorial! You're awesome.

In the previous example, we showed that 65535 + 1 = 0. If we subtract one from each side, we get 65535 = - 1. So symmetrically, this makes sense.

Same with the binary version. 0 is 0000 0000 0000 0000 in binary. If we subtract 1, then we get binary 1111 1111 1111 1111, which is 65535. We talk more about how integers convert to binary in chapter 3.

"-2^n-1" should be written as -(2)^n-1. Otherwise it implies that the first number in the range can be positive should the exponent be positive, which is impossible. Just a little syntax error :p

Good point. However, your solution is equally incorrect. :) It should be -(2^n-1), so the 2^n-1 part evaluates first, and then the negative is applied.

I've updated the lesson accordingly.