Texas Instruments Interview Question
Aditya's explanation isn't very accurate but he/she did get some points right.
Here's the breakdown.
i = 4
then it goes into the switch case.
since there isn't a defined case for the input it goes into the default case.
it runs the default case and because there wasn't a 'break;' defined, it continued right through case 3.
Which is why we end up adding 5 to i, making i = 9.
Skipping the 'if ( i == 8 )' statement.
then subtracting 4 from i, making i = 5.
then 'break' out of the switch case.
then onto 'printf()' which displayed 'i = 5'
We know switch case is base on continues flow without break statement. Here first control will come to default, where there is nothing to execute and no break as well, so it will come to case 3: where it will add 5 with original i value which is 9 now and there is condition if i==8, which is not true, so control will come to i-=4 and i value becomes 5, as there is one break statement after that line, control will come out of the scope and print the i value, which is 5... :)
Output will be 5 ..
- Aditya September 10, 2010as 'default' case is there on the top
hence it will execute the statement
i+=5
and i-=4;
after that it will get a break
and finally comes out of the block ..
I think basically interviewer was testing you C..
switch case is defined as
switch( i )
case a:
///code
break;
...
default
//code
break;
}