[Tutorial] Using the ternary operator :?

Started by SA:MP, May 05, 2023, 05:48 AM

Previous topic - Next topic

0 Members and 5 Guests are viewing this topic.

SA:MP

[Tutorial] Using the ternary operator :?

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. 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.


Code:

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..




Code:


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

... but not in any case.



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

Using if-statement.


Code:


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

Using ternary operator it looks like that.

Unfortunately not any statements are appropriate to be written using ternary operators like this one.

It might look quite weird.




Code:

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

In conclusion that's a brief tutorial how you can use ternary operators.



Unfortunately we tend to get crappy using ternary operators excessively.

It will be complicated to maintain code using ternaries especially for beginners.

You have to consider when to use it and not.

It might be useful to increase the readability of your code, but in other cases it might do the contrary.



So just use it when really necessary.



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

Source: [Tutorial] Using the ternary operator :?