![]() |
![]() |
#1 |
<optimized out>
Join Date: Sep 2020
Location: <optimized out>
Posts: 321
|
gcc and 64 bit, long long ints, not behaving for me?
I'm looking into using 64 bit long long ints in my code for one small part of a calculation that overflows a 32 bit int.
While trying them out I saw things that surprised me, so I started writing some test code. I've now got three functions to test what happens when the 64 bit numbers overflow. I think all three functions should behave the same, but they don't, only Test2 behaves as I expect and exits when the 64 bit number overflows and becomes negative. Can anyone explain why? Code:
typedef long long LONG64; void Test1(void) { KPrintF("Test 1:"); KPrintF("-------"); LONG64 x = 1; int i = 0; for (;;) { i++; x = 2 * x; if (x > 0) { KPrintF("1 - Yes: %ld", i); } else { KPrintF("1 - No: %ld", i); break; } } } void Test2(void) { KPrintF("Test 2:"); KPrintF("-------"); LONG64 x = 1; int i = 0; for (;;) { i++; LONG64 new_x = 2 * x; if (new_x > x) { KPrintF("2 - Yes: %ld", i); } else { KPrintF("2 - No: %ld", i); break; } x = new_x; } } void Test3(void) { KPrintF("Test 3:"); KPrintF("-------"); LONG64 x = 1; int i = 0; for (;;) { i++; LONG64 new_x = 2 * x; if (new_x > 0) { KPrintF("3 - Yes: %ld", i); } else { KPrintF("3 - No: %ld", i); break; } x = new_x; } } |
![]() |
![]() |
#2 |
Registered User
Join Date: Jan 2019
Location: Germany
Posts: 3,311
|
Your code triggers undefined behaivour as nothing is guaranteed if a signed type "overflows". The compiler can, for example, assume that a positive number times 2 is never becoming negative.
Note that this is different from unsigned numbers which are guaranteed to implement modulo arithmetics. |
![]() |
![]() |
#3 | |
<optimized out>
Join Date: Sep 2020
Location: <optimized out>
Posts: 321
|
Quote:
|
|
![]() |
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
Thread Tools | |
![]() |
||||
Thread | Thread Starter | Forum | Replies | Last Post |
Getting Registered - How Long?? | scrapser | project.WHDLoad | 8 | 05 May 2008 12:11 |
Towers (Warning, long shot and long post) | Drake1009 | Looking for a game name ? | 2 | 13 May 2005 00:11 |
has it really been so long?... | ShuDog | New to Emulation or Amiga scene | 4 | 29 April 2003 07:57 |
A very long, LONG shot... | staticgerbil | Coders. General | 0 | 13 April 2003 11:18 |
using latest snapshot...(a bit long) | supergoz | support.WinFellow | 3 | 12 December 2001 23:43 |
|
|