Thread: Whats better lots of stand alone if statements or if else statments?

  1. #1
    Registered User
    Join Date
    May 2023
    Posts
    3

    Whats better lots of stand alone if statements or if else statments?

    I am writing a program in where one function requires 4 if statements, is it better to write this like this
    Code:
    if(statement)
       code ... 
    
    if(statement)
        code ...
    or is it better to do
    Code:
    if(statement)
        code ....
    else if(statement)
        code ....

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Quote Originally Posted by africavoid View Post
    I am writing a program in where one function requires 4 if statements, is it better to write this like this
    Code:
    if(statement)
       code ... 
    
    if(statement)
        code ...
    or is it better to do
    Code:
    if(statement)
        code ....
    else if(statement)
        code ....
    It depends on the actual code.

    If the statement in the if() statements are related and is one of several choices, then the first might be the better choice. If the statements are not related than the second is probably better.

    Again, we would need to see actual code to better advise.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Every if is evaluated.
    Code:
    if(statement)
       code ... 
     
    if(statement)
        code ...
    
    if(statement)
       code ... 
     
    if(statement)
        code ...
    The first if to evaluate to true breaks the chain.
    Code:
    if(statement)
        code ....
    else if(statement)
        code ....
    else if(statement)
        code ....
    else if(statement)
        code ....
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with if statements and switch statments
    By Allen Sarkisov in forum C++ Programming
    Replies: 14
    Last Post: 02-08-2014, 12:17 PM
  2. whats wrong with the if statments
    By gamer in forum C++ Programming
    Replies: 5
    Last Post: 01-14-2004, 02:58 AM
  3. If Then Statments
    By BladeBoss2 in forum C Programming
    Replies: 6
    Last Post: 05-20-2002, 04:50 PM
  4. if statments
    By JPed2003 in forum C++ Programming
    Replies: 8
    Last Post: 05-10-2002, 07:58 PM
  5. whats wrong with my if statements
    By ssjnamek in forum C++ Programming
    Replies: 8
    Last Post: 01-29-2002, 12:48 AM

Tags for this Thread