A detailed explanation of the weird USES of switch

  • 2020-06-23 01:28:41
  • OfStack

I'm not going to summarize the switch usage here, but this is actually a quick and easy jump condition switcher. The most common technical discussion points for this feature are break and default after case. Instead of discussing these, look at the following code:


#include"stdio.h"
 
int main(void)
{
    int num = 0;
    switch(num)
    {
       printf("functionrun!\n");
    }
    return 0;
}

The above code USES 1 switch, but does not have any case or default in the code block. Is there a problem with the code syntax?

Compile 1 as follows:

E:\WorkSpace\02_ Technical practices \01_ programming language \01_C \02_C and Pointers \switch > gcc switch.c

E:\WorkSpace\02_ Technical practices \01_ programming language \01_C \02_C and Pointers \switch >

As you can see from the above results, there are no problems compiling. So what is the running state? Will the only printf execute the corresponding statement?

Run as follows:

E:\WorkSpace\02_ Technical practices \01_ programming language \01_C \02_C and Pointers \switch > a

E:\WorkSpace\02_ Technical Practices \01_ programming language \01_C \02_C and Pointers \switch >

So, it's a little weird. This printf statement is not executed! That is, the code execution in the switch statement must have the case tag indicating the entry of the code. This behavior is very reminiscent of the result of program execution in case 1. The code is as follows:


#include"stdio.h"
 
int main(void)
{
    int num = 0;
    switch(num)
    {
       int i = 123;
       printf("functionrun!\n");
       default:
           printf("value of iis:%d\n",i);
           break;
    }
    return 0;
}

The code was modified in the previous code. The second printf of the code will execute, but what is the value of i when executed? From the previous tests, the code behind the local variable is never executed, so will my i be initialized dynamically every time the function is executed here?

Code compilation and operation results:

E:\WorkSpace\02_ Technical Practices \01_ programming language \01_C \02_C and pointer \switch > gcc switch.c

E:\WorkSpace\02_ Technical practices \01_ programming language \01_C \02_C and pointer \switch > a value of i is:2

E:\WorkSpace\02_ Technical practices \01_ programming language \01_C \02_C and Pointers \switch >

Two conclusions can be drawn from the above results:

1, the declaration definition in the code block is in effect;

2. The value of i is not 123 to prove that the local variable of this part is not initialized dynamically every time.

Speaking of this, it is strange enough that I have seen a similar description when I read C Expert Programming before, but at that time I could not understand C Expert programming at the level of C. Just left a vague impression, as to whether it is a problem, free or will have to check.


Related articles: