I am writing code and it has a line where a, b, c, d are integers,
int a, b, c, d;
long long sum = a + b + c + d;
I get an overflow error, but after referring answer and modifying the sum as below lines which is in answer I didn’t get any problem:
long long sum = a;
sum += b;
sum += c;
sum += d;
For this line I get correct result. What is the difference?
Minion is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4
In the first case the expression:
a + b + c + d
Contains only int
s and therefore no conversion is done and the calculation is done in int
s (with potential overflow).
The fact that the result is used to initialize a long long
is not relevant because the expression is evaluated regardless of the initialization following it (the same would apply if it was an assignment instead of an initialization).
Only the result is converted when the initialization of sum
is performed.
In the second case lines like:
sum += b;
Are actually:
sum = sum + b;
And sum + b
is an expression containing both an int
and a long long
.
Therefore in order to evaluate it b
is converted to long long
and the overflow you had in the first case is not happening.
A side note:
In the posted code a
,b
, c
and d
are not initialized.
I assume that in your actual code they are.
2