Karthik Sagar
Karthik Sagar

Reputation: 444

Integer overflow and integer limits

I am a novice please help me to understand INTEGER OVERFLOW and working with INTEGER LIMITS in context of the following example. I am unable to interpret the output of the following code. I have considered three cases, directly printing , integers and unsigned long long integer.

#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;
}

OUTPUT:

Directly printing
0
0
2
-2
Using integer
0
0
2
-2
Using unsigned long long variables
0
0
2
18446744073709551614

Upvotes: 0

Views: 1212

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69854

tmp1 = -2*INT_MIN; undefined behaviour unless INT_MAX has twice the magnitude of INT_MIN (it won't).

tmp2 = 2*INT_MIN; undefined behaviour (overflowing a signed integer)

tmp3 = -2*INT_MAX; undefined behaviour unless INT_MIN has twice the magnitude of INT_MAX (it won't).

tmp4 = 2*INT_MAX; undefined behaviour (overflowing a signed integer)

temp1 = -2*INT_MIN; undefined behaviour (overflowing a signed integer)

temp2 = 2*INT_MIN; undefined behaviour (overflowing a signed integer)

temp3 = -2*INT_MAX; undefined behaviour (overflowing a signed integer)

temp4 = 2*INT_MAX; undefined behaviour (overflowing a signed integer)

Upvotes: 1

Related Questions