2

This question is probably stupid or paranoidal, but anyway :-). Given following code:

DWORD hiRes;

// will overflow about once in an hour
hiRes = GetTickCount() * 1193L;

If it known that hiRes overflows periodically and such situations are handled properly, is there anything wrong with this code?

UPDATE: Result is quite surprising for me, since the answer depends on the type of hiRes (signed or unsigned), which is defined by C Standard (see for example).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96

2 Answers2

6

Overflowing an unsigned int is safe. Overflowing a signed one isn't (undefined behavior).

MSDN says:

A DWORD is a 32-bit unsigned integer (range: 0 through 4294967295 decimal). This type is declared as follows:

typedef unsigned long DWORD

So it should be safe.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • DWORD is "typedef unsigned long DWORD;" in Windows. In what way signed owerflows are not safe? That's the difference with unsigned? – Petr Abdulin Aug 07 '11 at 09:06
  • 1
    They're unsafe in that the C standard says they're undefined behaviour. On a Windows platform though I don't think you're going to see anything unexpected. – john Aug 07 '11 at 09:09
1

Unsigned integers are safe, signed are not. But I've never come accross a platform that doesn't do the obvious twos complement thing. I do wish the standards people had bitten the bullet and just made it mandatory.

john
  • 85,011
  • 4
  • 57
  • 81
  • Any good compiler will optimize assuming your code does not invoke signed overflow. This means code that relies on predictable behavior from signed overflow is broken. – R.. GitHub STOP HELPING ICE Aug 07 '11 at 14:24
  • See also [exotic-architectures-the-standard-committee-cares-about](http://stackoverflow.com/questions/6971886/exotic-architectures-the-standard-committee-cares-about) :-) – Bo Persson Aug 07 '11 at 17:24