[Swan-dev] tricky arithmetic

D. Hugh Redelmeier hugh at mimosa.com
Sun Feb 1 00:35:07 EET 2015


| From: D. Hugh Redelmeier <hugh at mimosa.com>

| For similar reasons, changing the type of "borrow" to int is wrong
| too:
| 	borrow * 1000000  <==== can overflow

Not true.  I forgot that C chooses the smallest integral type that can
hold a literal.  So on a machine with 16-bit ints, 1000000 would have
type "long".  So the calculation would not overflow.

I used "unsigned long" for the calculation and representation of
microseconds.  If you want to choose the most efficient, uint32_t is
probably the right choice.  I strongly dislike specifying the number
of bits but is probably the best choice in this case.  You can format
it with the macro PRIu16.

uint20_t would be OK but it is rather obscure.  Maybe that's a good
thing.  But C compiler support is optional.

uint20fast_t, now that takes the cake.

Summary: unsigned long is fine.  int isn't.  uint32_t might be better.


More information about the Swan-dev mailing list