解释这个C程序的输出 [英] Explain output of this C program

查看:105
本文介绍了解释这个C程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发现这个code。在Ç拼图

Found this code at C Puzzles.

#include<stdio.h>

int main()
{
  int a=1;
  switch(a)
  {   int b=20;
      case 1: printf("b is %d\n",b);
              break;
      default:printf("b is %d\n",b);
              break;
  }
  return 0;
}

输出:

 b is 51

似乎无法理解这个输出。

Can't seem to understand this output..

推荐答案

您正在使用一个变量,一个不确定的值(调用未定义行为)通过跳过去变量的初始化 b 。该方案可以产生任何价值,这将是正确的。

You're using a variable with an indeterminate value (invoking undefined behaviour) by jumping past the initialization of the variable b. The program can produce any value and it will be correct.

C标准甚至包括这种情况下(在非规范性的例子)。

The C standard even covers this case (in a non-normative example).

7例中的人工程序片段

ISO/IEC 9899:2011 §6.8.4.2 The switch statement:

7 EXAMPLE In the artificial program fragment

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


  
  

其标识符的对象是 I 与自动存储时间(块内)存在,但绝不是
  初始化,因此如果控制前pression具有非零值,调用printf函数会
  访问一个不确定的值。同样,调用函数˚F无法达成。

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.

请注意了不确定的值'评论。

Note the 'indeterminate value' comment.


有一个关于访问一个不确定的值是否会导致不确定的行为的一些讨论的余地。在某些情况下(陷阱重新presentations),它可以导致未定义的行为。这将需要我一些时间来确定可能的不确定的行为'是否应该被视为不确定的行为。访问未初始化变量是一个坏主意,有什么可以说的是,印在你的code中的价值。

这篇关于解释这个C程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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