User Tools

Site Tools


one_line

One line If in C

A really handy way to write condensate and yet easily readable code in C is using one line if when doing only simple operation in the if.
There's two way of doing this, using a ternary operator (here ?) or a compact If syntax.

It is absolutely not recommended to use this syntax everywhere but when only incrementing a variable for example, it is great.

The ternary operator:

VARIABLE = (CONDITION) ? VALUE_TRUE: VALUE_FALSE;
syntax1.c
Variable = (Captor > Threshold) ? ValueIfTrue : ValueIfFalse;

A variation of this use case when using increment and decrement operators.

syntax2.c
(Variable > Threshold) ? Variable-- : Variable++;

The compact If syntax :

if (CONDITION) TRUE;
syntax3.c
if (Variable < 0) Variable = 0;
one_line.txt · Last modified: 2018/09/19 17:27 by supergnu