gpt4 book ai didi

c - 未初始化为 0 时的有趣值

转载 作者:行者123 更新时间:2023-11-30 18:47:45 25 4
gpt4 key购买 nike

我有以下代码,它应该在单独的行上显示每个输入单词。为了好玩,我放置了一个 printf 来显示每个单词后的字数,以确保我理解逻辑。

#include <stdio.h>

/*Write a program that prints its input one word per line*/

#define IN 1
#define OUT 0

int main()
{
int c, state, wordcount;

state = OUT;
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\t' || c == '\n')
{
if (state == IN)
{
printf("\n");
printf("Current word count: %i\n", wordcount);
/*troubleshooting*/
state = OUT;
}
}
else if (state == OUT)
{
state = IN;
putchar(c);
++wordcount;
}
else
{
putchar(c);
}
}
}

此图显示了此操作的输出。由于某种原因,没有将 wordcount 变量初始化为 0,它从 9 开始。

Wordcount variable gets set to 9 when it is not initialized to 0

当将 wordcount 变量初始化为 0 时(只需在 int 声明语句中设置 wordcount = 0),一切都会按预期工作:

Wordcount variable is correct when initialized to 0

有人可以向我解释一下这是怎么回事吗?这与这些变量在内存中的存储方式有关系吗?试图了解发生了什么事。谢谢!

最佳答案

在OP编辑问题之前:

这是未定义的行为。

if (state == IN)
//Some code
else if (state == OUT)
//Some code

看起来 State 在比较之前尚未初始化(或设置为值)。未初始化的值并不是未定义行为,但以这种方式访问​​绝对会引起 UB 的恐惧!

C89中,请参阅第 6.5.7 节初始化

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant

C99中,请参阅第6.7.8节初始化

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a null pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules; — if it is a union, the first named member is initialized (recursively) according to these rules.

引用standard section 6.3.2.1p2 :

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.

根据C99标准,它的“不确定值”,它要么是一个未指定的值,要么是一个陷阱表示。

但是,在了解这些标准提供的次要细节之前,您应该先了解一些最常见和最好了解的编码习惯。这可能是一个好的开始。

<小时/>

OP编辑后:

我从 OP 运行了完全相同的代码,其中 state = OUT;State 已初始化,它的行为方式应该如此。

标准输入:

Lazy Frog

输出:

Lazy
Current word count: 1
Frog
Current word count: 2

关于c - 未初始化为 0 时的有趣值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546497/

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