Article 4TDBF CodeSOD: Tern Down Service

CodeSOD: Tern Down Service

by
Remy Porter
from The Daily WTF on (#4TDBF)

In C, it's not uncommon to define a macro like this one:

#define MIN(a,b) (a>b?b:a)

It's useful to be able to quickly find the smallest of two numbers, and it's useful to do that with something a bit more readable than a ternary.

Of course, if you need to expand this to larger sets of numbers, it gets tricky. For example, maybe you need to find the smallest of three numbers.

Agripina recently had to track down some strange behaviors in an IoT device, and found this stack of ternaries:

int lowestVal(int a, int b, int c){ return a > b > c ? c : b ? b > c ? c : b : a;}

Three question marks is the mark of a great ternary mangling. The complete lack of any parentheses to group the expression to provide any sense of the actual logical flow is also great.

It's also entirely wrong.

This expression: a > b > c is a valid C expression, but it doesn't do what the mathematician who wrote this may have expected. The > returns 0 if the comparison fails, and 1 if it's true. Thus, if a = 10; b = 9; c = 2;, a > b results in 1, and 1 > 2 is also false, which results in 0.

This bug created all sorts of strange behaviors in the IoT firmware, and created a fair number of billable hours for Agripina in tracking down the source.

proget-icon.png [Advertisement] Ensure your software is built only once and then deployed consistently across environments, by packaging your applications and components. Learn how today! TheDailyWtf?d=yIl2AUoC8zAhyvvWK12xGg
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments