Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Conditional operator ?:

The ?: operator selects one of two expressions using a condition and supplies its value after required conversions.

Version: C23; repository compiler flag, production runtime not attested

Syntax

condition ? expression_if_true : expression_if_false

The ?: operator has three operands. It evaluates the scalar condition first. If the condition compares unequal to zero, it evaluates the expression after ?; otherwise, the expression after :.

Condition evaluation finishes before the selected branch. The other branch is not evaluated, but both must satisfy type constraints. Both branches determine the result type; arithmetic conversions can occur. The result is not an lvalue.

Nesting associates right: a ? b : c ? d : e means a ? b : (c ? d : e). In the example, count is zero, so division is skipped.

Examples

#include <stdio.h>

int main(void)
{
    int count = 0;
    int result = count != 0 ? 12 / count : 0;
    printf("%d\n", result);
    return 0;
}

Result

0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources