Interesting results of the quiz on integer arithmetic in C

Started by QL 1 month ago2 replieslatest reply 1 month ago112 views

The results of the EmbeddedRelated quiz on integer arithmetic in C are quite interesting (and will be even more interesting with more participants!) The success rate so far is only 8%. Considering that a bunch of random monkeys would achieve a success rate of about 20% (1 in 5 possible choices), it seems that embedded programmers must be somehow systematically wrong. What's going on?

[ - ]
Reply by Bob11November 4, 2022

Because only a random monkey would believe in the possibility that the compiler that runs most of the world's infrastructure could somehow pull a negative number out of an expression full of unsigned integers.

However, many C programmers (like myself) are lazy monkeys. I could smell an integer promotion trap as soon as I saw the code. In real life I'd rewrite the code to avoid any possibility of unsigned overflow or underflow because I know that dragons live there. However, in a quiz, it's easier to revert to pseudo-random monkey mode and guess the compiler would do something smart rather than look it up. That, of course, is always the wrong answer (as I was reminded myself). A random monkey can beat a pseudo-random monkey any day--ask any crypto expert :-)

The problem (dragons) is because the conversion rules (section A6 in K&R 2nd Ed) are arcane at best. A6.5 clearly states:

"Otherwise, if either operand is unsigned int, the other is converted to unsigned int. Otherwise, both operands have type int."

So, uint16_t is unsigned, so no problem. BUT, section A6.1 states:

"A character, a short integer, or an integer bit-field, ALL EITHER SIGNED OR NOT, or an object of enumeration type, may be used in an expression wherever an integer may be used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion." (Uppercase added to reveal hidden dragon.)

Now we find out that characters, short integers, and integer bit-fields are SPECIAL. They can magically change sign type like entangled quantum particles in your code determining whether your cat lives or dies. So, is uint16_t a short int or not? Only your cat knows, depending on which processor the code is targeting. This is why the once-bitten, twice-shy experienced monkeys avoid writing C code that overflows, and hate quizzes.

[ - ]
Reply by DilbertoNovember 4, 2022

"... and hate quizzes."