C Ternary Operators and are they better

Recently this was posted in a C for Embedded programming Linkedin group.

Attention C programmers!
Here’s a quick trick that can make your code more efficient and save you time. Did you know that you can use the ternary operator to simplify if-else statements?

For example, instead of writing:

if(x > 0){
y = 1;
}
else{
y = 0;
}

You can simplify it to:

y = (x > 0) ? 1 : 0;

This is particularly useful when you have multiple if-else statements within a loop. By using the ternary operator, you can make your code more readable and reduce the number of lines, leading to improved performance.

Give it a try and let me know what you think! 

C programming style for conditional code

Before you get all enthusiastic about this it is important to note that it is unlikely that the compiler will produce different or better machine executable code in the suggested case. It is really worth every software engineer spending time looking at the assembly code to see how little effect code shortcuts have. And this ternary construct is not allowed in some code standards. This paragraph was what I posted to the discussion.

The linkedin thread continued.

One person commented

“A neat trick, although I doubt that better performance would be a benefit. One should beware of premature optimization and overusing this technique. Code readability is king!”

Another added

“In my opinion, the use of ternary operator is often used and abused in places where it actually makes the code less readable. Some coding rules actually prohibit the use of the ternary operator altogether.”

One other person said politely

“sorry to give you this information, but even without any optimization the compiler will produce the same assembly, you can try by yourself using one of the different tools online such as https://godbolt.org/.”

It looks like godbolt.org might be a fun tool to allow software people to look at assembler for different compilers.

It is always good to look at the compiled output assembler code. It shows you what you have actually done.