songyujin

导航

关于Switch Case 的一点思考

Sometimes,we forget "break" statement when using "Switch Case". In this situation,what will happen? let's see the program as following.

int count1 = 0;
 int count2 = 0;
 int count3 = 0;
 int count4 = 0;
 int count5 = 0;
 char * s = "abcde";
 for(unsigned int i = 0; i < strlen(s) ;i++)
 {
  switch(s[i])
  {
  case 'b':
   count3++;
  case 'c':
   count4++;
  case 'd':
   count5++;
  default:
   count1++;
  case 'e':
   count2++;
  }
 }
 cout<<count1<<count2<<count3<<count4<<count5;
}

count1= 4,count2 = 5,count3 = 1,count4 = 5,count5 = 3

as a conclusion:
when case can't find matched char, it will execute default and the statement followed default.
else it will execute the matched statement and followed

posted on 2006-03-19 17:12  songyujin  阅读(1077)  评论(0编辑  收藏  举报