SA-MP Forums Archive
ternary operator - Printable Version

+- SA-MP Forums Archive (https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: ternary operator (/showthread.php?tid=495775)



ternary operator - SnL - 18.02.2014

pawn Code:
(var) ? (SendClientMessage(playerid,-1,"test 1")) : (SendClientMessage(playerid,-1,"test 2"))
I tried to learn about it but it game me error i'm missing


Re: ternary operator - Patrick - 18.02.2014

In ternary operator it looks like this.
pawn Code:
SendClientMessage(playerid, -1, ( var == 1 ) ? ("Test 1") : ("Test 2") );
//function -^        args^         if-^     then-^              ^-else
In else if it looks like this.
pawn Code:
if( var == 1) SendClientMessage(playerid, -1, "Test 1");
else SendClientMessage(playerid, -1, "Test 2");
Why do you want to use Ternary Operator? Why not use else if instead? it looks better and easier to read imo.


Re: ternary operator - SnL - 18.02.2014

Thank you +rep now i can understand.

What do you mean by 4-char?


Re: ternary operator - Patrick - 18.02.2014

Quote:
Originally Posted by SnL
View Post
Thank you +rep now i can understand.

What do you mean by 4-char?
4 Character, I had nothing to comment so I added 4-char to post my comment, although I edited my post and you should read it again.


Re: ternary operator - SnL - 18.02.2014

lmao ok
Because ternary operator is more faster than if-else if ( i readed it )


Re: ternary operator - GWMPT - 18.02.2014

Ternary operator processing speed is the same as the if / else statement. if not mistaken


Re: ternary operator - SnL - 18.02.2014

and why exists? if is the same as if ?
i read in a spanish tutorial that ternary operators works more fast than ifs


Re: ternary operator - GWMPT - 18.02.2014

Ternary operators exists to reduce the lines of code, and make the if statement somehow, more "flexible"[I can't describe it in a better word]

For example, you want to add "1" to the variable "randomvar" if the variable "tfalse" is true, or add "5" if the variable "tfalse" is false.
In the traditional programming, you would do this:
pawn Code:
if(tfalse)
    randomvar = 1;
else
    randomvar = 5;
So, with the ternary operator, you do:
pawn Code:
randomvar = (tfalse) ? 1 : 5;
Smaller, more "flexible", and it simply does what you need.


Re: ternary operator - SnL - 18.02.2014

Oh okay now i understand.
Thank you +rep.