# C++ max size of int

posted Jul 31 2 min read

In C++, int is one of the most frequently used data type along with other data types like float, double, char, … . In this article, I will show you the way to know size of an int variable and what we can do with its size.

We can simply get size of an int variable using following code:

``````#include <iostream>

using namespace std;

int main()
{
cout << sizeof(int);
}``````

And we got result: 4 (bytes). So what can we do with this information ?

1. Know the value range of an int variable

As I have mentioned above, size of an int is 4 bytes, and because 1 byte equals to 8 bits, so that size of int is also 32 bits. So an int variable can represent  2 ^ 32 – 1 = 4294967295 values.

However, because an int variable can represent both negative and positive values so in fact, it can only represent numbers from -2147483648 to 2147483647 (2^32 / 2 – 1).

In case of an unsigned int variable, as they can only hold values of non-negatives numbers so an unsigned in variable can represent number from to 4294967295 (2^32  – 1).

2. Get the number of elements in an array

If we know size of an element and size of the whole array, we can get the number of elements in the array using a simple arthimetic operation:

Number of elements = Size of array / Size of an element

Suppose that we have an array arr:

``int arr[] = {1, 2, 4, 5, 6, 3, 8, 9, 1, 2, 5, 7, 4, 3, 2, 4, 6, 7, 8, 9};``

Now we get size of the whole array (arrSize) and, because this is an array of integers, size of an int variable (elementSize).

``````int arrSize = sizeof(arr);
int elementSize = sizeof(int);``````

Finally, we can get the number of elements in the array:

``int n = arrSize / elementSize;``

Result: 20

Here is the completed code:

``````#include <iostream>

using namespace std;

int main()
{
int arr[] = {1, 2, 4, 5, 6, 3, 8, 9, 1, 2, 5, 7, 4, 3, 2, 4, 6, 7, 8, 9};

int arrSize = sizeof(arr);
int elementSize = sizeof(int);

int n = arrSize / elementSize;
cout << n;
}``````

I have shown you the size of int variables in C++ and what we can do with size of a variable. I hope this article will help you in your carreer.

Happy coding !