I am trying to do a division of :-
#include <bits/stdc .h>
using namespace std;
int main(){
int A = -2147483648;
int B = -1;
int C = A/B;
// this is not working
cout<<C<<endl;
// nor this is working
cout<<A/B<<endl;
// But this is working
cout<<-2147483648/-1<<endl; // printing the result 2147483648;
}
I am confused why this happening. Please explain.
CodePudding user response:
Assuming the int
type is 32-bits and uses two's complement representation, the first two cases exhibit undefined behavior because both -2147483648
and -1
fit in a int
but 2147483648
does not.
In the third case, the expression -2147483648/-1
contains the integer literal 2147483648
(before being negated), and has the first type in which the value can fit. In this case, that would be long int
. The rest of the calculation keeps the type, so no undefined behavior occurs.
CodePudding user response:
You can change the data type to long long.
long long A = -2147483648;
long long B = -1;
long long C = A/B;
If your you need fractional result, try 'double' instead of 'long long'.