[英]I don't understand how my compiler got this output in C++
My C++ program is as follows: 我的C ++程序如下:
#include<iostream>
#include<conio.h>
using namespace std;
int a;
struct CARE{
long L1;
void init()
{
L1=100;
}
void intake()
{
a++;
L1+=++a;
}
void takeout()
{
int k=5;
cout<<a*k<<'#'<<L1-a;
}
};
int main()
{
CARE c[3];
for(int i=0;i<3;i++)
c[i].init();
for(int j=0;j<3;j++)
c[j].intake();
for(int m=0;m<3;m++)
c[m].takeout();
return 0;
getch();
}
And the output comes out to be: 输出结果是:
30#9630#9830#100 30#9630#9830#100
According to me 'a' would be a junk variable and every output would be different from the other but that is not the case here. 根据我的说法,“ a”将是一个垃圾变量,每个输出都将与另一个不同,但是这里不是这种情况。 Can someone explain why? 有人可以解释为什么吗?
a
is at global scope, so it's initialised to 0
. a
在全局范围内,因此初始化为0
。
(Indeed if it was declared in a function then it would not be initialised and your program behaviour would be undefined.) (实际上,如果在函数中声明了它,则不会对其进行初始化,并且您的程序行为将是不确定的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.