Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Applications of Integer Types | Numerical Data Types
C++ Data Types

Sign up to start

or email

eye-icon

By continuing I agree with Terms & conditions,

 Privacy policy, Cookie policy

book
Applications of Integer Types

We found out that assigning a value exceeding the -2,147,483,648 to 2,147,483,647 range would not raise any error. Instead it will cause an overflow.

Remember

Overflow occurs when a calculation produces a result that is too large to be represented by the data type used.

For example, if you try to store a value larger than the maximum representable value for an integer type, an overflow will occur, and the result will wrap around or be truncated, leading to unexpected behavior in your program.

It can lead to critical bugs in your programs, so that's something to keep in mind. We will learn how to handle numbers that are too large in the next chapter.

Task

Swipe to start coding

  1. Fix the expression so it no longer causes an overflow.
  2. Change the order of operations, at first divide each number by 2 and only then add them.

Solution

cpp

solution

#include <iostream>

int main()
{
int first = 1502365230;
int second = 1262530350;
// The following code demonstrates a potential issue with integer overflow
// Although the final result will be within the range of an integer
// Adding two large numbers together can cause overflow before the division by 2 is performed
std::cout << first / 2 + second / 2 << std::endl;
}

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 2
#include <iostream>

int main()
{
int first = 1502365230;
int second = 1262530350;
// The following code demonstrates a potential issue with integer overflow
// Although the final result will be within the range of an integer
// Adding two large numbers together can cause overflow before the division by 2 is performed
std::cout << (first + second) / 2 << std::endl;
}
toggle bottom row
some-alt