在 switch 语句中初始化变量 [英] Initialize variables inside a switch statement

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

问题描述

#include <stdio.h>
int main(void) {
    int a = 1;
    switch(a) {
        int i = 2;
        case 1: printf("%d",i);
                break;
        default: printf("Hello\n");
    }
}

以下代码示例将 36 作为输出.这怎么可能?我知道编译器会直接将控制权转移到 case 1,而不评估 i.但是,为什么我得到的输出是 36?

The following code sample is giving 36 as the output. How is this possible? I understand that the compiler will transfer the control to case 1 directly, without evaluating i. But, why am I getting the output as 36?

PS:我正在使用 GCC.

PS: I am using GCC.

推荐答案

在 C++ 中,此代码格式错误,因为您无法跳转到变量的范围内.

In C++ this code is ill-formed because you cannot jump into the scope of a variable.

在 C 中,代码是未定义的行为:int i; 在 switch 块中存在,但是通过跳转到 case 1: 你绕过了值 2 将被分配给 i.所以实际上您正在尝试打印一个未初始化的变量.

In C the code is undefined behaviour: int i; inside the switch block exists, however by jumping to case 1: you bypassed the part where the value 2 would have been assigned to i. So in fact you are attempting to print an uninitialized variable.

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

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