AlliedModders

AlliedModders (https://forums.alliedmods.net/index.php)
-   Scripting Help (https://forums.alliedmods.net/forumdisplay.php?f=11)
-   -   if elseif else? (https://forums.alliedmods.net/showthread.php?t=216891)

vip-colgate 05-26-2013 22:59

if elseif else?
 
I knew that for a long time ago...
Code:

if( one ) ...
else if( two ) ...
else ...

and...
Code:

if( one ) ... return
if( two ) ... return
...

Can someone tell me what's the difference between them?
Which one is better? or no matter?

Blizzard_87 05-26-2013 23:04

Re: if elseif else?
 
this may not be best explanation but here goes.

PHP Code:

if( hasadmin1[id] ) {
    
execute command.... // if player hasadmin1 then command is done and others are ignored
}
else if( 
hasadmin2id ] ) {
    
execute command.... // if player does NOT have admin1 then this check is next....
}
else {
    
execute command... // if player does NOT have admin1 or admin2 then this command is executed.
}



if( 
hasadmin1id ] ) execute command....

if( 
hasadmin2id ] ) execute command....
// both of these checks will happen and if player has both admin1 and admin2 then both commands will execute . 


vip-colgate 05-26-2013 23:10

Re: if elseif else?
 
Are you sure?
Code:

if( one ) { ...; return; }
if( two ) { ...; return; }
...


ddhoward 05-26-2013 23:19

Re: if elseif else?
 
Quote:

Originally Posted by vip-colgate (Post 1959093)
Are you sure?
Code:

if( one ) { ...; return; }
if( two ) { ...; return; }
...



Yes.

Blizzard_87 05-26-2013 23:54

Re: if elseif else?
 
Quote:

Originally Posted by vip-colgate (Post 1959093)
Are you sure?
Code:

if( one ) { ...; return; }
if( two ) { ...; return; }
...


if your returning a value after the first IF then the others wont be checked.

but if your if check has more then 2 else if you should use a switch its better.

if( bla ){
...
}
else {
......
}

is ok for checking one or two things.

^SmileY 05-27-2013 08:16

Re: if elseif else?
 
IF you use only these statements for a function, you not need to use any return, like this:

PHP Code:

public client_authorized(id)
{
    if(
is_user_admin(id))
    {
        
g_Type 1;
    }
    else if(
is_user_hltv(id))
    {
        
g_Type 2;
    }
    else
    {
        
g_Type 0;
    }



fysiks 05-28-2013 00:18

Re: if elseif else?
 
Quote:

Originally Posted by vip-colgate (Post 1959087)
I knew that for a long time ago...
Code:

if( one ) ...
else if( two ) ...
else ...

and...
Code:

if( one ) ... return
if( two ) ... return
...

Can someone tell me what's the difference between them?
Which one is better? or no matter?

The latter (second one) is poor coding and might not work in all situations (i.e. it is context dependent). Always use the former.


All times are GMT -4. The time now is 16:18.

Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.