Using the ternary operator in PAWN/C

Ternary Operator


Ahoy everyone.
This time i’ll show you guys how to use the ternay operator given by many languages like C or PAWN.
This time we will only talk about the condititonal operator to replace if-statements. There are also ways to perform other actions using nested ternary operator statements.

It is commonly referred as the conditional operator, inline if (iif), or ternary if. An expression x ? y : a evaluates to y if the value of x is true, and otherwise to a.

Brief example, comparing 2 numbers using if-statement.


[pastacode lang=”c” manual=”new%20result%3B%0Anew%20a%3D1%3B%0Anew%20b%3D0%3B%0A%0Aif%20(a%20%3E%20b)%0A%7B%0Aresult%20%3D%20x%3B%0A%7D%0Aelse%0A%7B%0Aresult%20%3D%20y%3B%0A%7D” message=”” highlight=”5″ provider=”manual”/]


Using our beloved ternary operator makes it much simplier and shorter, and that’s it.


[pastacode lang=”c” manual=”result%20%3D%20a%20%3E%20b%20%3F%20x%20%3A%20y%3B%0Aresult%20%3D%20a%20%3C%20b%20%3F%20printf(%22a%20is%20less%22)%20%3A%20printf(%22a%20is%20greater%22)%3B” message=”” highlight=”1,2″ provider=”manual”/]


Now some examples from my gamemodes, in this case my spectate system to spectate a random player.
Using if-statement.

[pastacode lang=”c” manual=”if(!tmp)%20return%20INVALID_PLAYER_ID%3B%0Aif(idx%3Etmp)%20idx%3D0%3B%0Aif(idx%3C0)%20idx%3Dtmp-1%3B%0Areturn%20randoms%5Bidx%5D%3B” message=”” highlight=”” provider=”manual”/]


Now again to shorten this we’ll use ternary operator again.


[pastacode lang=”c” manual=”return%20(!tmp)%20%3F%20INVALID_PLAYER_ID%20%3A%20randoms%5B(idx%3Etmp)%3F0%3A((idx%3C0)%3F(tmp-1)%3Aidx)%5D%3B” message=”” highlight=”” provider=”manual”/]


So in conclusion we figured out we can economize letters using ternary operators instead of if-statement in some cases.

For now that’s it, but during the next days i’ll introduce some more advanced examples using the ternary operator in PAWN.

By Knogle

Convinced user of Linux operating systems since 2014. Started with FreeBSD and moved to Debian. Performed a preparatory course for Red Hat Certified System Administrator (RHCSA) certificate. Founder of Unix-Supremacy, formerly known as OpenKnogle Solutions, or Knogle Industries.
C and PAWN programmer, and experienced system and network administrator for complex enviroments.
Studying at RWTH Aachen University, majoring Computer Science and Electrical Engineering.
Loves to try out a lot of fancy stuff, and loves to give a little contribution to the Software Freedom Conservancy, the right to repair, and Open-Source software at all.

Leave a Reply

Your email address will not be published. Required fields are marked *