初学者程序员c++(本地vs全局变量声明)

时间:2022-06-16 16:49:32

I'm new to programming. I was trying to get the sum of the equation added to the previous value when I noticed some strange behavior.

我的新节目。我试着把方程和之前的值相加,这时我发现了一些奇怪的行为。

If I declare int result inside int main () then I get a blank answer, but if I declare int result outside int main () then I get these values: 6,11,16...91,96,101. It doesn't make sense to me since I have no other function.

如果我在int main()中声明int结果,就会得到一个空答案,但是如果我在int main()之外声明int结果,就会得到这些值:6,11,16…96,101。这对我来说毫无意义,因为我没有其他的函数。

Why does this happen?

这为什么会发生?

#include<iostream>
using namespace std;

int main ()
{
  int y =1;
  int result;

  while (result <100)
  {
     result = y +5;
     cout << result << ",";
     y = result;

  }
}

1 个解决方案

#1


5  

Within a function, int result; declares a variable named result, but doesn't initialize it to any particular value. Until you assign it a value it could be anything, and the behavior when reading from it is undefined. Thus when you read its value in your while condition it could be anything; your loop may execute or it may not. You need to supply an initial value for result to make the behavior of your program well-defined:

在函数内,int结果;声明一个名为result的变量,但不将其初始化为任何特定的值。在给它赋值之前,它可以是任何值,并且读取它时的行为没有定义。因此,当你读到它的价值时,它可以是任何东西;循环可以执行,也可以不执行。您需要为结果提供一个初始值,以使程序的行为得到良好定义:

int result = 0;

Unlike local variable, global variables are defined to be initialized to a default value when no initial value is explicitly provided, so when you read the value of result in your while condition, it is 0, and your loop executes.

与本地变量不同,全局变量定义为在没有显式提供初始值时初始化为默认值,因此当您在while条件中读取结果值时,它是0,并且执行循环。

#1


5  

Within a function, int result; declares a variable named result, but doesn't initialize it to any particular value. Until you assign it a value it could be anything, and the behavior when reading from it is undefined. Thus when you read its value in your while condition it could be anything; your loop may execute or it may not. You need to supply an initial value for result to make the behavior of your program well-defined:

在函数内,int结果;声明一个名为result的变量,但不将其初始化为任何特定的值。在给它赋值之前,它可以是任何值,并且读取它时的行为没有定义。因此,当你读到它的价值时,它可以是任何东西;循环可以执行,也可以不执行。您需要为结果提供一个初始值,以使程序的行为得到良好定义:

int result = 0;

Unlike local variable, global variables are defined to be initialized to a default value when no initial value is explicitly provided, so when you read the value of result in your while condition, it is 0, and your loop executes.

与本地变量不同,全局变量定义为在没有显式提供初始值时初始化为默认值,因此当您在while条件中读取结果值时,它是0,并且执行循环。