codedude
codedude

Reputation: 6519

Variable change in loop

So this is more of a theoretical question but here goes. Say I have the following C code:

for(parameter) {
    //do something
    if(condition) {
        variable = Value; 
    }
}

Say the loop runs several times and also say the condition is satisfied the first time it loops. But the second time it loops the condition is not satisfied. Does the variable still equal the value it was assigned in the first loop?

Upvotes: 0

Views: 923

Answers (1)

Alok Save
Alok Save

Reputation: 206508

Yes, unless you have changed the value explicitly it will be the value assigned in first iteration.

Note that this is only when the control is within the for-loop. Once control goes beyond the function, the value in variable will depend on it's storage class i.e: how it is declared. If it is a local/automatic variable it does not exist beyond the scope of the function { }, while if it is static it remains alive throughout the program lifetime and maintains the state as well.


I meant it as more of a why question

Because as a rule, variables in C and C++ retain their values while they are alive.

An automatic/local variable is alive within the scope { } in which it is defined. So it will retain the value assigned to it(unless explicitly changed) untill control remains within the scope.

static and global variables are alive throughout the program lifetime. So they retain the values assigned to them(unless explicitly changed) untill the program ends.

Upvotes: 2

Related Questions