Categories
Software

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.

 

new result;
new a=1;
new b=0;

if (a > b)
{
result = x;
}
else
{
result = y;
}

 

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

 

result = a > b ? x : y;
result = a < b ? printf("a is less") : printf("a is greater");

 

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

if(!tmp) return INVALID_PLAYER_ID;
if(idx>tmp) idx=0;
if(idx<0) idx=tmp-1;
return randoms[idx];

 

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

 

return (!tmp) ? INVALID_PLAYER_ID : randoms[(idx>tmp)?0:((idx<0)?(tmp-1):idx)];

 

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 *