Find maximum of three number in C without using conditional statement and ternary operator
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If the goal is to find the maximum of three numbers in C without if or the ternary operator, the cleanest trick is usually to build a branch-free max formula for two numbers and apply it twice. This is mostly an interview-style constraint, not something you would normally optimize for in production code.
A Math-Based Max Formula
For two integers, one common formula is:
That works because:
- If
a >= b, thenabs(a - b)becomesa - b - If
b > a, thenabs(a - b)becomesb - a
In C:
This avoids both conditionals and the ternary operator.
Extend It to Three Numbers
Once you can compute the maximum of two numbers, the maximum of three is just:
So the problem reduces naturally:
That keeps the code short and readable.
A Bitwise Alternative
Another class of solutions uses bit operations to avoid explicit branches:
Then:
This style is more "clever," but it is also less portable and easier to misunderstand because it depends on signed shift behavior and integer representation assumptions.
Why the Math Version Is Usually Better
For explanation purposes, the arithmetic formula is easier to justify than the bitwise trick. It makes the intent obvious and does not rely on reading sign bits manually.
However, it still has a caveat: the expression a + b or a - b can overflow for very large integers. In interview-sized examples that may be ignored, but in real systems it matters.
That overflow risk is one reason these branch-free formulas are usually treated as exercises rather than as broadly safe utility functions.
This Is Mostly a Constraint Exercise
In real C code, you would almost always write:
That version is clearer, easier to maintain, and less error-prone. The branch-free versions are mainly useful as a puzzle or to understand how arithmetic and bit tricks can encode comparisons.
Common Pitfalls
- Forgetting that
abs(a - b)can overflow for edge integer values. - Using signed bit-shift tricks without understanding portability implications.
- Solving the interview constraint and then treating the trick as generally better production code.
- Assuming branch-free code is automatically faster in every real compiler and CPU scenario.
Summary
- You can solve the problem without
ifor?:by computingmaxfor two values and reusing it. - The arithmetic formula with
absis the most readable trick. - Bitwise approaches exist but are harder to justify and maintain.
- These solutions are mostly puzzle-style exercises.
- In real code, clarity usually beats branch-avoidance tricks.

