Thread: switch

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    36

    switch

    Code:
    #include <stdio.h>
    
    int main()
    {
        int x=1;
        switch (x) {
        case 1 : printf( "x = 1\n" );
        default : printf( "x is an integer\n" );
        }
    }
    when i run this program "x is an integer " is printed. according to ansi is it supposed to be printed?

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    You should put a break statement at the end of every case unless you want it to run into the next case.
    Code:
    case 1 : printf( "x = 1\n" ); break;
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    36
    what i am asking is whether the 'default ' statement runs always or runs only when no other case is true.

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    20
    As XSquared said you need to put break; at the end of 'case 1' in order to prevent the 'default' statement to run if 'case 1' is correct. If you don't put it, then if 'case 1' is correct, also the 'default' will run, thus making the 'default' statement always run. Just use the break keyword when using switch.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by modec
    what i am asking is whether the 'default ' statement runs always or runs only when no other case is true.
    In your case, always, as described by other posts. When all others are false, it will always execute. (Unless you don't provide a default case, then nothing happens.)

    But, as illustrated, since you left out the break keyword, in your case, it will always execute.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. ascii rpg help
    By aaron11193 in forum C Programming
    Replies: 18
    Last Post: 10-29-2006, 01:45 AM
  3. Switch
    By cogeek in forum C Programming
    Replies: 4
    Last Post: 12-23-2004, 06:40 PM
  4. Switch Case
    By FromHolland in forum C++ Programming
    Replies: 7
    Last Post: 06-13-2003, 03:51 AM