Question about the "switch" statement

This is a discussion on Question about the "switch" statement within the C# Programming forums, part of the General Programming Boards category; Hey guys, quick question. When you use a switch statement, does it evaluate the condition once or every time it ...

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    6

    Question about the "switch" statement

    Hey guys, quick question.

    When you use a switch statement, does it evaluate the condition once or every time it is tested against a case? I imagine it would be the former, since that's much more efficient, but I need to make sure. For example:

    Code:
    switch (random.Next(0, 2))
    {
         case 0:
              foo();
              break;
         case 1:
              foo_2();
              break;
    }
    Would this code test each case against a different random number, or would it store the random number and then test it against each case? Either way it's a simple fix; if it's the former, I can just do:

    Code:
    int randomNumber = random.Next(0, 2);
    
    switch (randomNumber)
    {
         // stuff
    }
    The better code depends on when the switch statement and how the switch statement checks the cases. That's my question.

    Thanks in advance

  2. #2
    Registered User
    Join Date
    Jun 2010
    Posts
    6
    Nevermind that, found it out experimentally. It's like I thought; the condition is saved and remains a constant when being compared to the cases. So, a condition that returns a different value each time (e.g. random.Next(MIN, MAX)) can safely be checked against each case.

  3. #3
    essence of digital xddxogm3's Avatar
    Join Date
    Sep 2003
    Posts
    589
    when all else fails, use the debugger to look at the values at run time.
    "Hence to fight and conquer in all your battles is not supreme excellence;
    supreme excellence consists in breaking the enemy's resistance without fighting."
    Art of War Sun Tzu

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about break in switch statement
    By alone2002dj in forum C Programming
    Replies: 1
    Last Post: 12-09-2007, 07:42 PM
  2. Quick IF statement question (beginner)
    By jim.rattlehead in forum C Programming
    Replies: 23
    Last Post: 11-29-2007, 05:51 AM
  3. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  4. Usefulness of the "else if" statement
    By gn17 in forum C Programming
    Replies: 7
    Last Post: 08-12-2007, 05:19 AM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 02:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21