Thread: if,else if and else confusion...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    11

    if,else if and else confusion...

    Hi. Can anyone explain these threee? I know that condition if doesnt work, it goes to else. Else ifs are confusing me however....when do I use if, else if and only if -else? Thanks. I really sadly need to grasp the logic behind this. Examples to each would be great!

  2. #2
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317
    Else ifs are used when only one of a group of possible choices is valid. If a else if b else if c
    the expression is evaluated until one is true then the rest are skipped instead of having to compare each one
    if a
    if b
    if c
    even if a is true is still compares b and c
    Last edited by manofsteel972; 10-10-2004 at 07:00 PM.
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    I consider else ifs to be redundant in a lot of situations. For example, if I was testing multiple choice values stored in a char, the else doesn't matter (except maybe for speed) because the condition will evalute to false anyway. With the else, the condition and it's corresponding code is compeltely ignored.

    NOTE: Although in the above example it's probably better to use a switch statement anyway.

  4. #4
    ---
    Join Date
    May 2004
    Posts
    1,379
    Code:
    if (a<b)
      ...
    else if (a==b)
      ...
    else
      ...
    just an example

  5. #5
    Registered User
    Join Date
    Sep 2004
    Posts
    11
    Gee, thanks alot guys. The explanation cleared up a lot of confusion in my head regarding that subject.

  6. #6
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    NOTE: Although in the above example it's probably better to use a switch statement anyway.
    If what you comparing can't be reduced down to a single integer value you won't be able to use switch and will have to use another control structure.

Popular pages Recent additions subscribe to a feed