23.01.2019, 14:35
(
Last edited by faxxe; 23/01/2019 at 05:26 PM.
)
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; }
Code:
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.
Code:
if(!tmp) return INVALID_PLAYER_ID; if(idx>tmp) idx=0; if(idx<0) idx=tmp-1; return randoms[idx];
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)];
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.