2

Could anyone please explain why the output of this code is 4 when x = 0 ( i thought if x is 0, which applies the the case 0: and y suppose to be 3 and i'm wrong in this case.

#include <stdio.h> int main() { int x = 0; int y; switch (x) { case 0: y = 3; case 1: y = 4; break; default: y = 5; break; } printf("%d", y); getchar(); return 0; } 
2
  • IMHO, the best way to see switch() is as a "computed GOTO" Commented Nov 19, 2014 at 23:58
  • There should be a list of 'You're a C programmer Harry - when" and 'face palmed because of a fall-through bug in a switch statement you coded' is on it. Commented Nov 20, 2014 at 0:05

4 Answers 4

3

After switch(x) operation, execution jumps to the corresponding case N statement first. Then it executes code after that statement until a) it find the end of the switch(x) boundary defined by brackets ({}) or b) it finds a break statement inside the switch, which ends that switch.

In your case it went through y=3 down to case 1, down to y=4 and then ended at the break.

Sign up to request clarification or add additional context in comments.

Comments

2

Case statements are designed to fall through to the next case in line unless they have a break statement to pull execution out of the entire switch. In this case you commended out the break statement for "case 0", so execution slipped downward to "case 1" which reassigned y to 4.

Comments

2

You commented out your break; statement in your first case statement!

So just write this:

(Otherwise when x is 0 or 1 y gets assign to 3 and then 4)

case 0: y = 3; break; 

A switch statement goes to the next break; if there is missing one for a case statement! An if you forgot all of them :D then it stops at then end of the switch statement and all lines get's executed!

2 Comments

Yes but i need to know how this work when there's no 'break;'
@Impalerz if there is no break statement it goes until the next one!
1

Because the break is commented out:

switch (x) { case 0: y = 3; //break; <---- commented out. 

And to every novices surprise execution just carries on from the 'matching' case unless a break (or return) is encountered.

I'm sure it seemed like a good idea at the time and there are some really fruiting coding tricks that exploit it. Duff's device is the most famous.

http://en.wikipedia.org/wiki/Duff's_device

999 times out of a 1000 it's an annoying bug that will take an hour to find.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.