News for hackers. Stuff that matters.
Re:A Quiz About Integers in C by klodolph on Monday June 04, 2012 @01:47AM (#4062825)
Hm, okay... the intro text apparently disappears as soon as you click start.
Re:A Quiz About Integers in C by sausagefeet on Monday June 04, 2012 @02:32AM (#4062909)
Specifying those things is really weak anyways. "Here is a portability test on how the standard defines int's, but oh, assume this implementation".
Re:A Quiz About Integers in C by pdw on Monday June 04, 2012 @04:14AM (#4063103)
I don't think it's intended as a portability test, but rather an implementation-defined vs undefined behavior test. And in practice it's safe to make assumptions about implementation-defined behavior as long as you're programming for general-purpose computers.

Regehr clarifies this in the comments section: "Regarding signed overflow being defined or not, compiler developers generally draw a sharp distinction between undefined behavior and implementation-defined behavior. 32-bit ints, 2's complement, etc. are examples of the latter and signed overflow is an example of the former. A lot of developers do not draw such a sharp distinction, which is why I made a point of asking questions about this issue."

Re:A Quiz About Integers in C by klodolph on Monday June 04, 2012 @04:40AM (#4063155)
For an example of signed overflow versus unsigned overflow, certain compilers are known to assume that int loop variables won't overflow. So "for (int i = 0; i != -1; ++i)" is transformed into "for (int i = 0; ; ++i)", since both are equal in the eyes of the C standard (both will iterate through all non-negative values that fit in an int, then both will invoke undefined behavior, so they are the same).

The funny part is that it's often better to use int exactly because of the undefined behavior on overflow. By signaling to the compiler that you don't intend to overflow a particular variable, it can optimize appropriately.

Re:A Quiz About Integers in C by gpvos on Monday June 04, 2012 @03:22AM (#4063009)
Things are pretty bad when even on the most well-known platform, with a fairly straightforward implementation of two's complement integers, the answers are not intuitive.
Re:A Quiz About Integers in C by klodolph on Monday June 04, 2012 @04:52AM (#4063182)
Fortunately, with a few simple coding guidelines you can avoid major pitfalls.

1. Always do bit operations on unsigned types.

2. Never overflow signed types.

3. Always shift less than the type width. I can name architectures which implement large shifts in three distinct ways.

4. Know that most integers get promoted to int or unsigned, so you need an explicit cast to get 64 bits on most platforms. So 1ULL << 48 is okay, 1U << 48 is bad.

5. Treat unsigned int / unsigned long as contagious, just like float and double.