Introduction
So, an integer overflow is a computing error where, when a number gets too large (mainly >9223372036854775807; it could be >2147483647 that causes a problem), it will try to roll over.
Why doesn’t it go on forever?
Computers count in binary. In computer software, usually an Integer function will have 64 bits, although some (like Minecraft) only have 32.
I’ve heard of computers going to 18.446 quintillion!
That’s because those integers are unsigned. Most integers are signed.
How does the actual overflow happen?
So, as we know, computers count in binary. In signed processes, it goes up to 9223372036854775807, or more rarely, 2147483647. Since you are a novice, I won’t scare you with 64 bits. Here’s how it happens:
0000 0000 0000 0000 0000 0000 0000 0000 is 0
0000 0000 0000 0000 0000 0000 0000 0001 is 1
0000 0000 0000 0000 0000 0000 0000 0010 is 2
…
0111 1111 1111 1111 1111 1111 1111 1101 is 2147483645
0111 1111 1111 1111 1111 1111 1111 1110 is 2147483646
0111 1111 1111 1111 1111 1111 1111 1111 is 2147483647
1000 0000 0000 0000 0000 0000 0000 0000 is -2147483648!?
It went negative because in a signed process, the first bit (the 1 in 1000 0000 0000 0000 …) determines the sign. A 0 means + and a 1 means -.
What about my case?
Your case:
#include<iostream>
#include<limits.h>
using namespace std;
int main()
{
int tmp1=0,tmp2=0,tmp3=0,tmp4=0;
unsigned long long temp1=0,temp2=0,temp3=0,temp4=0;
cout<<"Directly printing"<<endl;
cout<<-2*INT_MIN<<endl<<2*INT_MIN<<endl<<-2*INT_MAX<<endl<<2*INT_MAX<<endl;
cout<<"Using integer"<<endl;
tmp1 = -2*INT_MIN;
tmp2 = 2*INT_MIN;
tmp3 = -2*INT_MAX;
tmp4 = 2*INT_MAX;
cout<<temp1<<endl<<tmp2<<endl<<tmp3<<endl<<tmp4<<endl;
cout<<"Using unsigned long long variables"<<endl;
temp1 = -2*INT_MIN;
temp2 = 2*INT_MIN;
temp3 = -2*INT_MAX;
temp4 = 2*INT_MAX;
cout<<temp1<<endl<<temp2<<endl<<temp3<<endl<<temp4;
}
This is wrong as multiplying an INT_MIN or INT_MAX by a number not -1, 0 or 1 will result in an Overflow. You are trying to multiply INT_MIN and INT_MAX by 2 and -2. Please remember that INT_MIN is the minimum, you can’t go below it and INT_MAX is the maximum, you can’t go above it.
<limits.h>is the C header, not that it matters, but you might want to take a look at<limits>that has e.g.std::numeric_limits<int>::max()unsigned long longvariables before they are initialized. In the "Using integer" section you print the values oftemp1etc., when you should be usingtmp1etc. Try to use better variable-naming and these things hopefully won't happen that much. Also, a good compiler would have issued warnings about this.