The same problem happens with gcc -O2 and gfortran -O2, respectively with the programs:
#include <stdio.h>
int main() {
int n = 1626, i, j, s = 0;
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
s += i * j;
}
}
printf("%d\n", s);
return 0;
}
program bug
integer :: n = 1626, i, j, s = 0
do i = 1, n
do j = 1, n
s = s + i * j
end do
end do
print *, s
end program
With gcc -O2, I get the message
bug.c: In function 'main':
cc1.exe: warning: iteration 1623u invokes undefined behavior [-Waggressive-loop-optimizations]
bug.c:5:5: note: containing loop
for(i = 1; i <= n; i++) {
^
With gfortran -O2, I get instead
f951.exe: Warning: iteration 1623 invokes undefined behavior [-Waggressive-loop-optimizations]
bug.f90:3:0:
do i = 1, n
^
note: containing loop
This warning seem to appear only for n >= 1626, and only with -O2 or higher.
I got this behaviour with both the x86-win32-dwarf and x86-64-win32-seh compilers (in the "Personal Builds/mingw-builds/" directory), for versions 4.9.3, 5.2.0 and 5.3.0 in the sourceforge repository, but not with the version 4.8.5.
Hmm, s overflows (-2147432845) at i==57 and j==1130, but yes gcc4.8 doesn't warn.
Interesting, with "unsigned" instead of "int" in the C program, I get no warning. So actually, the compiler is clever enough to see there will eventually be an undefined behaviour due to integer overflow. Thanks.
This should probably be closed to a gcc PR.
On May 11, 2016 6:17 AM, "Jean-Claude Arbaut" telephore@users.sf.net
wrote:
Related
Bugs: #539