Doubt in C

priyabc's Avatar, Join Date: Feb 2007
Light Poster
Code:
int i=3;
switch(i)
{
   default:
      printf("zero");
      break;
   case 1:
      printf("one");
      break;
   case 2:
      printf("two");
      break;
   case 3:
      printf("three");
      break;
}
the result obtained for this code is three.. what is the reason..

i think zero might be the result since the default statement comes before the other case statement.. so a soon as it enters the switch it might execute the statements within default and exit the switch on seeing the break statement ... therefore zero will be the output... but it is not why...?????

what happens exactly during the execution????
help me friends!!

Last edited by shabbir; 12Aug2007 at 06:25.. Reason: Code block - http://www.go4expert.com/forums/misc.php?do=bbcode#code
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Look, the first thing you need to do is read the "Before you make a query" thread. It tells you to use code tags to retain the formatting of your code. Failing to do so is being rude to the people from whom you are seeking free help.

It does not enter the default case because i matches one of the cases, namely 3. It is working as it should.

This is three "doubt" posts. You need to read a dam' book, son.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by DaWei
This is three "doubt" posts. You need to read a dam' book, son.
Get a good book in C.
0
kaustubh's Avatar, Join Date: Aug 2007
Go4Expert Member
Priya,
you have declared that int i = 3;
therefore the c compiler will take i =3 ;
if you say int i ; or int i = 0;
then it will go to default .
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by kaustubh
if you say int i ; or int i = 0;
It will go for default only when its not initialized and when int i =0; its initialized.
0
kaustubh's Avatar, Join Date: Aug 2007
Go4Expert Member
Your right i forgot.
0
indian.21987's Avatar
Light Poster
default statement can be placed anywhere in the loop.
But it will be executed only when all the cases didn't match.