Using the ternary operator in PAWN/C

Veröffentlicht von Knogle am

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.

Kategorien: Software

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.