HN
Today

Side-Effectful Expressions in C (2023)

This technical piece delves into C's side-effectful expressions like assignment and increment/decrement operators, arguing they often hinder readability and lead to obscure behavior despite their terseness. The author breaks down classic C idioms, revealing how intermingling computation and side effects can complicate code comprehension. It's a deep dive into language design philosophy that resonates with Hacker News's audience passionate about programming language internals and code clarity.

4
Score
0
Comments
#9
Highest Rank
4h
on Front Page
First Seen
Mar 23, 4:00 PM
Last Seen
Mar 23, 7:00 PM
Rank Over Time
1791624

The Lowdown

The author critically examines certain side-effectful expressions in C, such as assignment and pre/post-increment/decrement operators, contending that while they offer brevity, they frequently compromise code readability and can introduce subtle bugs. The article frames this discussion around the fundamental distinction between statements and expressions, advocating for a clearer separation of computation and side effects.

  • The piece begins by contrasting expressions (trivially nestable, for computation) with statements (sequential, for side effects), suggesting that mixing side effects into expressions makes C code harder to reason about.
  • It highlights how C's lax rules, like undefined evaluation order in expressions involving multiple side effects on the same variable (e.g., ++x * powi(x, 2)), lead to non-obvious and often undefined behavior.
  • Through examples like powi(), K&R's itoa(), and memcpy(), the author demonstrates how common C idioms utilizing these side-effectful expressions can be rewritten into more explicit, statement-based forms for improved clarity.
  • The article also addresses 'Yoda conditions,' where accidental assignment within an if statement condition can lead to silent bugs, recommending explicit comparisons (10 == x) as a preventative measure.
  • While acknowledging the 'unquestionable elegance' and terseness of certain constructs (e.g., s[i++] and while (n--) *d++ = *s++), particularly in specific contexts like byte processing, the author ultimately argues against their widespread use.

Ultimately, the author concludes that for most cases, the reduction in readability and understandability caused by these side-effectful expressions outweighs the benefits of their brevity, suggesting they should ideally be restricted to contexts where they function purely as statements.