Right, signed integer overflow is undefined in C. Try using -fwrapv to make the compiler treat it more sanely, or do your arithmetic using unsigned types and just cast to a signed type at the end.
--David Grayson On Mon, Dec 9, 2024, 11:46 AM Hannes Domani via Mingw-w64-public < mingw-w64-public@lists.sourceforge.net> wrote: > Am Montag, 9. Dezember 2024 um 19:50:19 MEZ hat Johannes Khoshnazar-Thoma > <johan...@johannesthoma.com> Folgendes geschrieben: > > > Hi: > > > > When compiling following C program: > > > > #include <stdio.h> > > > > int main(int argc, char ** argv) > > { > > volatile unsigned long long a = 0; > > volatile unsigned long long b = a + (1ULL << 63); > > > > if (((long long) a - (long long) b) >= 0) > > printf("wrong\n"); > > else > > printf("right\n"); > > > > return 0; > > } > > > > with mingw gcc compiler: > > > > /home/johannes/.zeranoe/mingw-w64/x86_64/bin/x86_64-w64-mingw32-gcc > --version > > x86_64-w64-mingw32-gcc (GCC) 12.3.1 20230814 > > > > and -O2 the output of the program is: > > > > wrong > > > > When compiling without -O2 or compiling on another gcc (the one that > comes > > with Linux Ubuntu for example) the result is: > > > > right > > > > Is the above comparision in the C program something that is undefined? > > > > Looking at the assembly code the difference seems to be the > > conditional jump expression: it is > > > > js .L4 > > > > in the right case and > > > > jl .L4 > > > > in the wrong case. > > > > My 8086 assembly is almost about 35-40 years old, however I recall > > that jl jumps if operand 2 is less than operand 1 (in System-V > > syntax ...). > > > > Is this maybe a mingw gcc bug? > > UBSAN [1] says it's undefined behavior, and I would tend to agree: > > example.c:8:24: runtime error: signed integer overflow: 0 - > -9223372036854775808 cannot be represented in type 'long long int' > > [1] https://godbolt.org/z/TcvYsec8j > > > Hannes > > > _______________________________________________ > Mingw-w64-public mailing list > Mingw-w64-public@lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/mingw-w64-public > _______________________________________________ Mingw-w64-public mailing list Mingw-w64-public@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/mingw-w64-public