Home > Back-end >  C of a for loop in the life cycle of independent variables
C of a for loop in the life cycle of independent variables

Time:09-27

First defines a structure body
Structure has some properties such as Int string, etc.
Then I each loop in the for loop statements a structure, why in the end of each loop structure when the structure of life seems to have no end?

 
Typedef struct test
{
int a1;
Int a2;
String b;
} the test;

Int main () {
for(int i=0; i <5; I++) {
The test c;
If (I==0) 1=7 c.a.;
If (I==1) c.a. 2=8;
If (I==2) mount="test";
If (I==3) printf (" % d/n ", c.a. 1);
If (I==4) printf (" % d/n ", c.a. 2);
}
}



If not defined in the structure of type string when don't I==2 statement complains that no initialization,
But when the structure of type string, it is no longer an error says no initialization, but also the output of the normal 7 and 8;
And the structure of the string is set after the third cycle is empty, but why hasn't the int type?

CodePudding user response:

for(int i=0; i <5; I++) {
The test c;//c is a temporary variable, its life cycle will be ended after each cycle,
If (I==0) 1=7 c.a.;//loop to a1 assignment for the first time, 2 times, a1 cannot guarantee or 7, but didn't say not 7,
If (I==1) c.a. 2=8;//the so-called using an uninitialized variable, also is the value of the variable is not affirmatory,
If (I==2) mount="test";
If (I==3) printf (" % d/n ", c.a. 1);//the two sentences in the printf, c hasn't been initialized, the principle of printed things could be any value,
If (I==4) printf (" % d/n ", c.a. 2);//
}

This example, the c values may be right, that's because the object c stored on the stack, the function is simple enough, loop stack space has not been changed,
Pay attention to the object of the life cycle, do not use an uninitialized object,

CodePudding user response:

String b; Each loop can be initialized again into an empty string,

Because if you don't have to write the default constructor, then the system will generate a default constructor for the object, the default constructor invokes the members,

But for the int char * built-in types, such as its default constructor, don't do anything,

Each loop will call a test object constructor and destructor, thinking this way, you will be able to understand what is going on,
  • Related