Author Topic: [TUTORIAL] How to use ternary operators to shorten code.  (Read 281 times)

greentarch

  • Global Moderator
  • Newbie
  • ********
  • Posts: 16
  • Reputation: 0
    • View Profile
[TUTORIAL] How to use ternary operators to shorten code.
« on: April 21, 2013, 09:19:55 pm »
Hi, this is a tutorial how to use Ternary Operators.

Let's use an example :
Code: [Select]
new
    a = 0;

if ( a == 0 ) {
    a = 1;
}
else {
    a = 2;
}

Can be shorten to :
Code: [Select]
new
    a;

a = (a == 0) ? 1 : 2;

Let's break it out.
Code: [Select]
a = (a == 0)   ?   1   :   2;

--
( a == 0 ) -> If a == 0
--
? -> Then
--
1 -> Set it to 1. ( No ';' here )
--
: -> Else
--
2; -> Set it to 2. ( Now, there's a ';' here )
--
That was easy!

More examples :
Code: [Select]
SetPlayerTeam( playerid, ( pro[ playerid ] == true ) ? TEAM_PRO : TEAM_NOOB );

SendClientMessage( playerid, -1, ( pro[ playerid ] == true ) ? ( "You are a pro." ) : ( "Noob." ) );
                                                                                             // ^ you need brackets for strings
Hope I helped.
« Last Edit: April 21, 2013, 09:22:10 pm by greentarch »

Share on Bluesky Share on Facebook


Fitri

  • Newbie
  • *
  • Posts: 11
  • Reputation: 1
    • View Profile
lol i can't understand :3


xian

  • Administrator
  • Newbie
  • **********
  • Posts: 8
  • Reputation: 0
    • View Profile
You need to practice more about this and you'll eventually know this. :3

Zero Nub Scripter

  • Newbie
  • *
  • Posts: 3
  • Reputation: 0
    • View Profile
Ahh............ Cookieh

KiNG3

  • Global Moderator
  • Newbie
  • ********
  • Posts: 10
  • Reputation: 0
    • View Profile
I think of it like math to be honest, not that complicated is it?

greentarch

  • Global Moderator
  • Newbie
  • ********
  • Posts: 16
  • Reputation: 0
    • View Profile
Yes, it is like math. And it's not that complicated if you understand :)