Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ for loop variable lifetime is weird

for(int i = 0; i < 3; i++)
{
    for(int j = 0; j < 3; j++)
    {
        int n;
        n++;
        printf("n : %d\n", n)'
    }
}

The output of the code is 1 2 3 4 5 6 7 8 9. I'm wondering why the variable n in the for loop isn't initialized when the variable declaration is executed.

like image 775
paganinist Avatar asked May 10 '15 04:05

paganinist


People also ask

Does for loop check condition every time?

Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.

What type of variable is used in a for loop?

In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure.

What is the scope of a variable in a for loop?

In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.

What is lifetime of variable in C++?

C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."


2 Answers

You're never initializing n to a specific value. C++ will not do this by default when you call int n. Instead, it just reserves an integer sized block of memory. So when you call n++, the program is just grabbing whatever value happens to be in that memory and incrementing it. Since you're doing this in quick succession and not creating new variables in between, it happens to be grabbing the same memory over and over. As @NicolasBuquet points out, compiler optimization may also be responsible for the consistency with which the same chunk of memory is picked.

If you were to assign a value to n, (i.e. int n = 1;) this behavior would go away because a specific value will be written to the chunk of memory assigned to n.

like image 102
seaotternerd Avatar answered Oct 17 '22 03:10

seaotternerd


In C++, no variable is initialized with a default value; you must specify one explicitly should you find the need to do so.

The result of your code is really undefined; it is just pure luck that you are getting the numbers 1 through 9 in sequence. On some other machine or implementation of C++, you might get different results.

like image 45
thesentiment Avatar answered Oct 17 '22 03:10

thesentiment