Earlier I came up with something, which I solved, but it got me later
let’s take a look at a similar example of what I was on:
int b = 35000000; //35million
int a = 30000000;
unsigned long n = ( 100 * a ) / b;
Output: 4294967260
I simply changed a to unsigned long and the correct 85% output would come up, because a is a signed 32bit integer. But this got me later. There is no value assignment to a during ( 100 * a ) there is just simply a calculation and the correct value which is 3billion should come up instead of an overflow. To understand if there wasn’t really an assignment to a I removed a from the code and manually write the value instead instead:
int b = 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
The big surprise was that the output is also: 4294967260
And of course value of 3billion can be assigned to an unsigned long.
My first thought was that ( 100 * 30000000 ) was causing an overflow, but then I asked “an overflow on what? there is nothing to be overflowed”.
Then I changed b to unsigned long, which even most suprisingly the output was correct 85%.
In the first example changing a to unsigned long
int b = 35000000;
unsigned long a = 30000000;
unsigned long n = ( 100 * a ) / b;
and leaving bas an int as it is works, but on the second example it doesn’t, what is occuring?
This might be a little overwhelming to let me re-write all examples with the ones who work and the ones who dont.
Works (Output = 85):
int b = 35000000;
unsigned long a = 30000000;
unsigned long n = ( 100 * a ) / b;
Works (Output = 85):
unsigned long b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
Doesn’t works (Overflow):
int b = 35000000;
int a = 30000000;
unsigned long n = ( 100 * a ) / b;
Doesn’t works (Overflow):
int b = 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
Let me explain what is occuring here.
On:
The value is incorrect because overflow happens at
( 100 * 30000000 )But on:
The value is correct, so what is happening?
In the first example
bis aint, as said by Tony, an overflow happens because the register where the temporary value of( 100 * 30000000 )will be assigned is able to hold 32bit signed integers, that happens because 100 is an int and 30000000 is also an int AND becausebis also an int, the register in this case are smart, when ALL values on the right side areintit assumes the values also have to be anintbut when a mightyunsigned longcomes to the party, it knows that dividing anintby anunsigned long,/ bis wrong, so it stores the value of( 100 * 30000000 )to anunsigned long.