switch 语句的问题 [英] Issue with switch statement

查看:26
本文介绍了switch 语句的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通过代码看问题:

code-1

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a =1;
    switch (a)
    {
        printf("This will never print\n");
    case 1: 
        printf(" 1");
        break;
    default:
        break;
    }   
    return 0;
}

此处 printf() 语句永远不会执行 - 请参阅 http://codepad.组织/PA1quYX3.但是

Here the printf() statement is never going to execute - see http://codepad.org/PA1quYX3. But

code-2

#include <stdio.h>
int main(int argc, char *argv[])
{
    int a = 1;
    switch (a)
    {
        int b;
    case 1:
        b = 34; 
        printf("%d", b);
        break;
    default:
        break;
    }   
    return 0;
}

这里将声明 int b - 参见 http://codepad.org/4E9Zuz1e.

Here int b is going to be declared - see http://codepad.org/4E9Zuz1e.

我不明白为什么在 code1 printf() 中不执行但在 code2 int b 中会执行.

I am not getting why in code1 printf() doesn't execute but in code2 int b is going to execute.

为什么?

我得到了 int b;是声明,它在编译时分配内存,因此无论控制流是否到达那里,都将完成该声明.

现在看这个代码

#include<stdio.h>

int main()
{
   if(1)
   {
    int a; 
   }

a =1;
return 0;
}

这里的 int a 仍在控制流路径中,但这不会编译......为什么?

here int a is in control flow path still yet this not going to compile...why?

推荐答案

switch 想象成一个带有标签的 goto.goto 在哪里都没有关系,只要变量声明在你使用它的上面,你就可以使用它.这部分是因为变量声明不是一个像表达式一样完成"的可执行语句.该开关几乎相当于:

Think of switch as just a goto with labels. It doesn't matter where you goto, as long as a variable declaration is above where you use it, you can use it. This is partially due to the fact that a variable declaration is not an executable statement that gets "done" like an expression. That switch is very nearly equivalent to:

int a  = 1;

{
    if (a == 1) goto case1;
    goto defaultcase;

    int b;

case1:
    b = 34;
    printf("%d", b);
    goto end;

defaultcase:
    goto end;

end:
}

return 0;

而且 gotob 的作用域无关.

And the gotos have nothing to do with the scope of b.

尝试这样做:

switch (a)
{
int b = 1;
....

在这种情况下,即使声明了 b,初始化也将被跳过,因为 是一个可以完成或不完成的可执行语句.如果您尝试这样做,您的编译器应该警告您.

In that case, even though b is declared, the initialisation will be skipped because that is an executable statement that can either be done or not done. Your compiler should warn you if you try to do that.

关于 if 中的声明(更新问题): 在这种情况下,a 的范围仅限于 if.进入作用域时创建,作用域结束时销毁.

Regarding the declaration inside if (updated question): In that case, a has a scope limited to the if. It is created when the scope is entered, and is destroyed when the scope ends.

这篇关于switch 语句的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆