Thread: Cannot understand SWITCH statement

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    2

    Cannot understand SWITCH statement

    I am new to C and am taking the C course by the C++ Institute. It seems I am not as smart as I thought.

    This program returns 4, but I cannot understand why:

    Code:
         #include <stdio.h> 
         int main(void) { 
             int i = 3, j = i - 2; 
             switch(i - 2) { 
             case 1: j++; 
             case 2: j++; 
             case 0: j++; break; 
             default:j = 0; 
             } 
             printf("%d",j); 
             return 0; 
         }
    It seems that j increments at each case statement. But why is it so?

    I would expect the i - 2 condition to evaluate to 1, the program to execute case 1: j++, then printf("%d",j); to be called, with j = 2.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Notice that only case 0 has a break statement.

    What you're seeing is fall-through.
    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.

  3. #3
    Registered User
    Join Date
    Feb 2017
    Posts
    2
    I see. Thank you for your reply.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 'If' Statement inside the Switch statement being ignored.
    By howardbc14 in forum C Programming
    Replies: 4
    Last Post: 04-11-2015, 11:45 AM
  2. Help me understand this while( ) statement
    By euclid in forum C Programming
    Replies: 14
    Last Post: 02-04-2012, 08:19 AM
  3. Help me understand following statement/syntax in C++
    By sanddune008 in forum C++ Programming
    Replies: 1
    Last Post: 04-22-2011, 10:29 PM
  4. Cannot understand this FOR statement!
    By MicroB in forum C Programming
    Replies: 3
    Last Post: 12-13-2010, 04:28 AM
  5. Need help to understand this statement
    By jk1998 in forum C++ Programming
    Replies: 3
    Last Post: 04-20-2007, 02:42 PM

Tags for this Thread