A conditional expression as an operand loses its parentheses #59

Closed
opened 2026-10-08 18:43:15 +02:00 by alex-eg · 1 comment
Owner
(/ (* 100.0 matched) (if (> compared 0) compared 1))

emits (100.0 * matched) / (compared > 0) ? compared : 1, which C
parses as ((100.0 * matched) / (compared > 0)) ? compared : 1.
Clang only warns (-Wparentheses). This one computes wrong values
silently, so it is the most dangerous entry here. Bound to a variable
first, it's right.


Found with sexc dfafe8b while building vs-map-viewer (from its Sex-field-notes.org).

```scheme (/ (* 100.0 matched) (if (> compared 0) compared 1)) ``` emits `(100.0 * matched) / (compared > 0) ? compared : 1`, which C parses as `((100.0 * matched) / (compared > 0)) ? compared : 1`. Clang only warns (-Wparentheses). This one computes wrong values silently, so it is the most dangerous entry here. Bound to a variable first, it's right. --- Found with sexc `dfafe8b` while building vs-map-viewer (from its `Sex-field-notes.org`).
alex-eg added the bug label 2026-10-08 18:43:15 +02:00
Author
Owner

Clang warns only when the operator ends up in the condition, as in the example above. When the conditional comes first, the rest of the operand moves into the else branch, and that is valid C nothing warns about. A sweep of vs-map-viewer found four such sites that had compiled cleanly with -Wall -Wparentheses:

  • (malloc (* (if (> w h) w h) (sizeof u32))) emitted malloc((w > h) ? w : h * sizeof(u32)): when w > h, a buffer a quarter of the size, so a heap overflow on every wide box blur.
  • (+ (if (< d -4) -4 (if (> d 4) 4 d)) 4) gave an index of -4, an out-of-bounds write that corrupted a neighbouring array of counts and with it a figure in the project's docs.
  • (* (if (> depth 40) 40 depth) 255) gave water deeper than 40 blocks the shallow colour.
  • (cast (if ...) float) cast only the condition; harmless there.

Only the generated C showed them. The workaround is the same: bind to a variable first.

Clang warns only when the operator ends up in the condition, as in the example above. When the conditional comes first, the rest of the operand moves into the else branch, and that is valid C nothing warns about. A sweep of vs-map-viewer found four such sites that had compiled cleanly with `-Wall -Wparentheses`: - `(malloc (* (if (> w h) w h) (sizeof u32)))` emitted `malloc((w > h) ? w : h * sizeof(u32))`: when `w > h`, a buffer a quarter of the size, so a heap overflow on every wide box blur. - `(+ (if (< d -4) -4 (if (> d 4) 4 d)) 4)` gave an index of -4, an out-of-bounds write that corrupted a neighbouring array of counts and with it a figure in the project's docs. - `(* (if (> depth 40) 40 depth) 255)` gave water deeper than 40 blocks the shallow colour. - `(cast (if ...) float)` cast only the condition; harmless there. Only the generated C showed them. The workaround is the same: bind to a variable first.
Sign in to join this conversation.