basics · beginner · ~10 min

Three-way classify using ternary

Use `?:` for compact conditional expressions.

Challenge

Return the sign of an integer as -1, 0, or 1, using the ternary (?:) operator.

Task

Implement int sign(int n) that returns -1 when n is negative, 0 when n is zero, and 1 when n is positive. Express the three-way decision with the conditional operator ?:.

Input

A single signed int n.

Output

Returns -1, 0, or 1 according to the sign of n.

Example

sign(5)    ->   1
sign(-3)   ->   -1
sign(0)    ->   0

Edge cases

  • INT_MAX returns 1 and INT_MIN returns -1.
  • Avoid tricks like n / abs(n) — that is undefined when n is 0 (and abs(INT_MIN) is undefined).

Rules

  • Use the ternary operator; a one-line expression suffices.

Why this matters

A nested ternary is the cleanest way to express a 3-way decision; recognising when it improves readability vs hurts it is a real skill.

Input format

A single signed int n.

Output format

-1, 0, or 1 according to the sign of n.

Constraints

Use the ternary operator; one expression. Don't divide by n.

Starter code

int sign(int n) { /* TODO */ return 0; }

Common mistakes

Returning n / abs(n) — undefined for n == 0.

Edge cases to handle

0, INT_MAX, INT_MIN.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.