Skip to content

#if: ?: treats a zero condition as true unless it is written exactly as 0 #726

Closed

Description

@danmar

constFoldQuestionOp checks the condition by comparing strings (condTok->str() != "0"). A condition that is zero but not written exactly as 0 is taken as true, so the wrong branch is chosen. Examples are 00, -0, and -X
where X is not defined (it folds to -0).

Wrong branch, no division:

#if 00 ? 0 : 1
yes
#else
no
#endif

gcc/clang: yes. simplecpp: no. #if -0 ? 0 : 1 gives the same result.

Since #722 the condition also decides which operand is not evaluated, so an error in the branch that should be evaluated is silently dropped:

#if 00 ? 1 : 1/0
yes
#endif

gcc/clang: error, division by zero in #if. simplecpp: yes, no error. The same happens with #if -0 ? 1 : 1/0, and with #if -X ? -1 : (0%0) ? 1 : 2 where X is undefined.

&& and || (constFoldLogicalOp) already use stringToLL(...) != 0 and handle these values correctly. ?: should use the same check, stringToLL(condTok->str()) != 0.

For the fix, test cases for 00 ? 0 : 1, -0 ? 0 : 1, 00 ? 1 : 1/0 (should error) and -X ? 0 : 1 with X undefined would cover it.

Activity

  1. added theissue type on Nov 7, 2026
  2. added a commit that references this issue on Nov 9, 2026
    9f5687e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions