gpt4 book ai didi

c - C中的自动存储类

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:41 24 4
gpt4 key购买 nike

在C语言中,自动存储类变量的初始值是垃圾值。但是以下列方式声明的变量每次都为所有此类变量提供 0,而它应该是垃圾值。

auto int i;
printf("%d",i);

最佳答案

auto int i;
printf("%d",i);

这里不需要关键字auto;它指定了一个默认的存储类。

上述代码的行为是明确未定义的。参见 N1570 6.3.2.1 第 2 段。措辞有点密集,但它描述了一个左值(基本上是一个指定对象的表达式)如何“转换”为存储在对象中的值——在这个情况下,相关对象是i

If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

存储在 i 中的值是任意的,在实践中检索该值很可能会给你一些看起来像 int 值的东西,但是 该访问的行为是未定义的,这意味着标准没有说明实际发生的事情。编译器可以完全拒绝该程序,或者 printf 调用的输出原则上可能是蓝色的超智能阴影(后者不太可能)。

如果访问检索存储在该内存块中的任何值,则 0 与任何其他值一样可能,甚至可能更多。明天运行同一个程序时,您可能会得到不同的值。

(N1570 是 2011 ISO C 标准的最新公开草案。)

关于c - C中的自动存储类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39796888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com