Problem in switch statement in C

soodsandeep
soodsandeep used Ask the Experts™
on
Hello experts, i have a small problem in understanding the behavior of switch statement.
i am attaching a small code. that outputs 811. how does it do ?
Please explain.

Thanks.
main ( )
{
	int a = 1;
	clrscr( );
	switch(a)
	{
		int b= 88 ;
		case 1:
			printf("%d",b) ;
			break;
		default:
			printf("%d",b) ;
	}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
I get 0, not 881.
If you move the int b= 88 ; to line 3, you should get 88

Commented:
You can't get a single 8 and a double 1. There is no instruction to print 1 and no instruction to print just a single 8.
Agree with phoffric.

What environment are you using to program? Check your active project and make sure you're not running other projects.
switch statement
switch(Variable)
{
     case value:
                                          doanything();
                                           break; // used to stop the switch -ENDS it.
     case value:
                                          doanythingelse();
                                           break; // used to stop the switch -ENDS it.
    default:
                                 doanything();

}
it is like a switch button
first you start the switch by assigning your variable to the function
switch(a)
then you tell the compiler from where it should start and where to end using { }
switch(a)
{

}
now we use case value - it is like you say if a is equal to this value then execute the statements after :
switch(a)
{
 case 1:
puts("a is equal to one");
}
then we use break to end the switch to tell it to stop we dont want it to check anymore.
switch(a)
{
case 1:
puts("a is equal to one");
break;
}
we usually use too many cases so what if they all failed then we should have defualt case that is why we use defualt:
switch(a)
{
case 1:
puts("a is equal to one") ;
break;
case 2:
puts("a is equal to two") ;
break;
default:
puts("sorry");
}
I hope i helped you to understand and sorry for the broken english.
regards.
To clarify, I just happen to get 0, not 811. In any environment, b is not initialized, so you get whatever happens to be on the stack. 811 is just as reasonable as any other uninitialized value.
The C99 standard says:
"A switch statement causes control to jump to, into, or past the statement that is the
switch body, depending on the value of a controlling expression, and on the presence of a
default label and the values of any case labels on or in the switch body. A case or
default label is accessible only within the closest enclosing switch statement."


So, your switch(a) jumps to either your case statement or to your default statement.

"In the artificial program fragment (from the standard - modified a little by me and shown below), the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached."

OUTPUT:
$ ./a
expr = 1  i = 0

Then change expr initialized to 0:
$ ./a
expr = 0  i = 17


#include <stdio.h>

void f(int val) {
   printf("val = %d\n", val); 
}
int main ( )
{
   int expr = 1;
   switch (expr)
   {
      int i = 4;
      f(i);
   case 0:
      i = 17;
      /* falls through into default code */
   default:
      printf("expr = %d  i = %d\n", expr, i);
   }
   return 0;
}

Open in new window

Commented:
I totally agree with everything phoffric said. The variable b is uninitialized when it's printed, so any output is possible.

In a switch statement, what you put at the top will not get executed.

Author

Commented:
phoffric,
i am using Turbo C version 3.0
jagomezb,
>> In a switch statement, what you put at the top will not get executed.
then why does not compiler give error that b is not declared ?
>> In a switch statement, what you put at the top will not get executed.
>> then why does not compiler give error that b is not declared ?
I have VS 2008 Express and Cygwin. Neither give a compiler error. In post http:#33129961 is code that is cut from the C99 standard. And there is no indication that a compiler error should be issued. Oddly, in C99, as you can see from the description, the code is syntactically correct. Yet, as the standard explains, storage "exists with automatic storage duration (within the block) but is never initialized" and the function doesn't get executed. Looking elsewhere in C99 standard, it appears that it throws switch syntax along with while and for where you can have a block defined by curly braces { }.

I am guessing that there is no error as a compromise to compiler vendors who would have to do extra work to make a special case for the switch. Although the compiler allocates automatic storage within the block, the jump to the case prevents the initialization and f(i) from being executed. It is just code that is skipped over.

I think it should be an error condition since it is very misleading.

Now, if you were to make line 11
    static  int i = 4;
then the output would be:
$ ./a
expr = 1  i = 4

Adding static means that i is allocated storage and initialized before the main() function is called. The scope of i is still within the switch block.

Commented:
Very nice explanation phoffric.

"el que sabe, sabe"
"case bypasses the initialization of local variable" error  appears..
it all depends on compiler..
some compilers will bypass that declaration of b..
and will give u an error"variable not declared"
declaration inside switch-case isn't allowed. So flashes error. Make the declaration out side switch, u will get 88 as the o/p which is expected.

main ( )
{
      int a = 1;
        int b = 88 ;
      clrscr( );
      switch(a)
      {
            
            case 1:
                  printf("%d",b) ;
                  break;
            default:
                  printf("%d",b) ;
      }
}
can any one tell how the static or global variables initialized before main() function called?
Hello nagireddyA,
This should be a different question.
Commented:
The only logical explanation is:
Switch with "cases" is similar to an GOTO label, so when you b declaration and initialization has never happend for this program, I think it's printing rubbish from the memory, because there is no other explanation.

Try compiling it with BCC32(an ANSI C compiler).
You should give us the compiler you are using.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial