Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Doubt in C (http://www.go4expert.com/forums/doubt-in-c-t5810/)

priyabc 12Aug2007 01:38

Doubt in C
 
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!!

DaWei 12Aug2007 06:09

Re: Doubt in C
 
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.

shabbir 12Aug2007 06:26

Re: Doubt in C
 
Quote:

Originally Posted by DaWei
This is three "doubt" posts. You need to read a dam' book, son.

Get a good book in C.

kaustubh 13Aug2007 17:42

Re: Doubt in C
 
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 .

shabbir 13Aug2007 17:46

Re: Doubt in C
 
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.

kaustubh 13Aug2007 21:57

Re: Doubt in C
 
Your right i forgot.

indian.21987 20Aug2007 19:53

Re: Doubt in C
 
default statement can be placed anywhere in the loop.
But it will be executed only when all the cases didn't match.


All times are GMT +5.5. The time now is 23:09.