https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96538
Bug ID: 96538 Summary: Integer overflow when there are multiple operands in addition operation. Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: prateek_kd at yahoo dot co.in Target Milestone: --- I am trying to add int values present in the vector and store in long int type variable. If I am using for loop for calculating the sum of vector elements program produces correct sum. However if If I perform direct addition(e.g sum= arr[0]+arr[1]...=arr[n]), the results obtained is incorrect and seems that overflow is occurring. Below is the code snippet for you reference: Input:942381765 627450398 954173620 583762094 236817490 Code leading to overflow/error: #include<bits/stdc++.h> using namespace std; int main() { vector<int> arr(5); for(int i=0;i<5;i++) { cin>>arr[i]; } sort(arr.begin(),arr.end()); long int sum = 0,min_sum=0,max_sum=0; sum = arr[1]+arr[2]+arr[3] min_sum = arr[0]+ sum; max_sum = arr[4]+ sum; cout<<min_sum<<" "<<max_sum<<endl; return 0; } Output :-1904555549 -1187199419 Code producing correct output: #include<bits/stdc++.h> using namespace std; int main() { vector<int> arr(5); for(int i=0;i<5;i++) { cin>>arr[i]; } sort(arr.begin(),arr.end()); long int sum = 0,min_sum=0,max_sum=0; for(int j=0;j<5;j++) { sum = sum+ arr[j];//after for loop sum = arr[1]+arr[2]+arr[3] } min_sum = arr[0]+ sum; max_sum = arr[4]+ sum; cout<<min_sum<<" "<<max_sum<<endl; return 0; } Output(for same input as above): 3581402857 4298758987