Thread: switch or if

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    82

    switch or if

    I'm getting an input from a user - a number - 1 or 2, and then test if it's 1 or 2. Should I use switch or if? I think switch is better because I can also define a default case, but then - I can do the same with if: if, else if, else. Which one should I use and how do I know in other cases as well?
    Last edited by lmanukyan; 01-19-2016 at 08:32 AM. Reason: missed a part of question

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    If the program has to act on a discrete set of values (do this for 1, do that for 2, etc), then a switch is usually better.

    If the program has to act on a range of values (for 1 through 10, do this, for 11 - 20, do that), then an "if-else" is usually better.

    If the only inputs you are expecting is 1 and 2, then either would be sufficient.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help with Switch
    By thirbur in forum C Programming
    Replies: 15
    Last Post: 05-09-2012, 11:49 PM
  2. A switch that doesn't switch
    By Death_Wraith in forum C++ Programming
    Replies: 5
    Last Post: 11-06-2004, 12:18 PM
  3. switch
    By modec in forum C Programming
    Replies: 4
    Last Post: 05-19-2003, 05:09 PM
  4. If-else OR switch
    By Juganoo in forum C Programming
    Replies: 6
    Last Post: 11-16-2002, 10:56 AM
  5. Switch
    By jk81 in forum C Programming
    Replies: 1
    Last Post: 11-13-2002, 09:35 PM