开发者

c switch statement

void display()
{
    printf("every thing is ok");
}
void main()
{
    int ch;
    while(1)
    {
        printf("enter your choice");
        scanf("%d",&ch);
        switch(ch)

        {
            cas开发者_StackOverflow中文版e 1: clrscr();printf("when choice is one every thing is fine");
                    display();
                    break;
            case 2: clrscr();printf("when chice is two its confusing");
                    display();
                    break;
            case 3: exit(0);
            default: printf("enter choice as 1 or 2 or to exit enter 3");
        }
    }
}

When I trace this C program and enter the choice as 2 it calls the display function from the case 1 block. I do not understand this. Please reply with an explanation. I am really confused.


The compiler is probably re-arranging your source statements collapsing its basic blocks. The debugger then matches calls to display() in both cases to the same source line number. This is usual when optimization is enabled.


Your compiler may be doing something fancy with optimization when it sees the same function call in two different cases. Check your compiler flags, and/or add some differing arguments to display() to see whether it really gets called as you specify.


Compilers transform code to make it more efficient. This can be confusing when you are trying to debug, so you should probably turn off optimizations (how to do this depends on your compiler or IDE).

If you notice in your code that after the printf statements case 1 and case 2 are identical, then you should realize that it may be more efficient to just have one call to display -- one of the cases will just jump to the last statement of the other case and the program's results are the same.

You can go a lot further than that, though. Since the only real difference between case 1 and case 2 is the string that is printed you could have only one copy of the entire block of code except for a little bit of code that sets a pointer to the string that will be printed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜