简体   繁体   中英

I don't understand how my compiler got this output in C++

My C++ program is as follows:

#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

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. Can someone explain why?

a is at global scope, so it's initialised to 0 .

(Indeed if it was declared in a function then it would not be initialised and your program behaviour would be undefined.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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