http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58417
Bug ID: 58417
Summary: Incorrect optimization
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: mirzayanovmr at gmail dot com
Created attachment 30820
--> http://gcc.gnu.org/bugzilla/attachment.cgi?id=30820&action=edit
Compile it with "g++ -O2 a.cpp" and run. It will output 0 instead of 10.
The following code writes 0 (but 10 is expected) with -O1 or -O2. Checked on
4.7.2 and 4.8.1 (mingw), on Fedora with g++ (GCC) 4.8.1 20130603 (Red Hat
4.8.1-1).
Command line to compile: g++ -O2 a.cpp
Code:
#include<iostream>
using namespace std;
long long arr[6] = {0, 1, 2, 3, 4, 5};
int main()
{
int n = 5;
long long sum = 0, prevsum = 0;
for(int i = 1; i <= n; i++)
{
cout << "sum = " << sum << endl;
sum = (i - 1) * arr[i] - prevsum;
// cout<<"sum : "<<sum<<endl;
prevsum += arr[i];
}
cout << "Final Result: " << sum << endl;
}