简体   繁体   English

未初始化为0时的有趣值

[英]Interesting Value When Not Initialized to 0

I have the following code which is supposed to display each input word on a separate line. 我有以下代码,应该在单独的一行上显示每个输入的单词。 For kicks, I placed a printf to display the word count after every word to make sure I understood the logic. 对于踢,我放置了一个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);
        }
    }
}

The output for this is shown in this picture. 此输出显示在此图片中。 For some reason, without initializing the wordcount variable initially to 0, it starts at 9. 由于某种原因,没有将wordcount变量初始初始化为0,它就从9开始。

Wordcount variable gets set to 9 when it is not initialized to 0 未将Wordcount变量初始化为0时,它会将其设置为9

When initializing the wordcount variable to 0 (just setting wordcount = 0 in the int declaration statement), everything works as expected: 将wordcount变量初始化为0时(只需在int声明语句中将wordcount设置为0),一切都会按预期进行:

Wordcount variable is correct when initialized to 0 初始化为0时Wordcount变量正确

Can someone explain to me what is going on here? 有人可以告诉我这是怎么回事吗? Does this have something to do with how these variables are stored in memory? 这与这些变量在内存中的存储方式有关吗? Trying to understand what is going on. 试图了解正在发生的事情。 Thanks! 谢谢!

Before the OP edited the question: 在OP编辑问题之前:

This is Undefined Behavior. 这是未定义的行为。

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

It looks like State is not initialized (or set to a value) before comparing it. 在比较状态之前,似乎State未初始化(或设置为值)。 Leaving a value uninitialized is not Undefined Behavior, but accessing this way is definitely way to get in horrors of UB! 保留未初始化的值并不是未定义的行为,但是以这种方式访问​​绝对是引起UB恐惧的方法!

In C89 , see section 6.5.7 Initialization . 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 如果没有显式初始化具有静态存储持续时间的对象,则将其隐式初始化,就好像每个具有算术类型的成员都被分配了0,而每个具有指针类型的成员都被分配了一个空指针常量

In C99 , see section 6.7.8 Initialization 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. —如果它是一个联合,则根据这些规则(递归)初始化第一个命名成员。

Refer standard section 6.3.2.1p2 : 请参阅标准第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. 如果左值指定了可以使用寄存器存储类声明的自动存储持续时间的对象(从未使用其地址),并且该对象未初始化(未使用初始化器声明,并且在使用前未对其进行任何赋值) ),则行为未定义。

According to C99 Standard, its "indeterminate value", it is either an unspecified value or a trap representation. 根据C99标准(其“不确定值”),它可以是未指定的值或陷阱表示。

But, before you get into the minors details these standards provide, you should acquire some of the most common and good-to-know coding habits. 但是,在深入了解未成年人这些标准提供的详细信息之前,您应该掌握一些最常见且众所周知的编码习惯。 This can be a good start. 这可能是一个好的开始。


After the edit from OP: 从OP编辑后:

I ran the exact same code from OP which has state = OUT; 我从state = OUT; OP运行了完全相同的代码state = OUT; ie State initialized, it behaves the way it should. State初始化,它的行为应有的方式。

stdin: 标准输入:

Lazy Frog

Output: 输出:

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

If you initialize a variable, it gets a "random" (unused) allocation in your RAM, if something has been already written there, the variable uses this value for itself. 如果初始化变量,则它将在RAM中获得“随机”(未使用)分配,如果已经在其中写入了内容,则变量将使用该值本身。

That's why you always declare variables. 这就是为什么您总是声明变量的原因。

The backend is a bit more complicated, but thats the "simple" explanation. 后端有点复杂,但这就是“简单”的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM