https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96538
--- Comment #1 from Prateek Khade <prateek_kd at yahoo dot co.in> --- (In reply to Prateek Khade from comment #0) > 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=1;j<4;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