ColorDeColor
ColorDeColor

Reputation: 181

Why is this C++ code WORKING when it SHOULDN'T?

I am learning C++ using Robert Lafore's book ( OOP with C++ ). In the book, I have encountered this example:

#include <iostream>
#include <conio.h>

using namespace std;

void main ()
{
    int numb;

    for ( numb = 1 ; numb <= 10 ; numb++ )
    {
        cout << setw(4) << numb;
        int cube = numb*numb*numb;
        cout << setw(6) << cube << endl;
    }

    getch();
}

The variable 'cube' has been declared as int 'inside the loop body'.

int cube = numb*numb*numb;

Since the loop iterates 10 times, the variable 'cube' will also get declared 10 times. 'cube' is accessible inside the loop body no matter what iteration. So, when we enter the loop body for, say, 2nd iteration, 'cube' is already known( because it already got declared during the 1st iteration), and another declaration for 'cube' should give an error of "redefinition". But instead, it builds successfully and debugs without a problem. Why?

Upvotes: 1

Views: 483

Answers (7)

The variable cube is only used inside the body of the for loop. I am not sure that saying it is declared ten times is correct (a declaration, actually a definition in your case, is a syntactic and static textual portion of source code).

In C++ you can (and you often do) have blocks with local variables. The scope of cube starts at it declaration and ends at the end of the containing block (braces { ... }).

If the type of a defined variable has a constructor, it is called at the definition point. If that type has a destructor, it is called conceptually at the end of the block (figuratively, just before the closing } ....).

Upvotes: 5

Subhajit
Subhajit

Reputation: 320

The variable 'cube' is declared and defined in each iteration. The scope of 'cube' dies with the iteration and new declaration and definition in each loop happens.

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

The scope of an automatic variable (such as cube) is the block in which it is declared. The block that cube is declared in is the body of the for loop. At the end of each iteration, the cube variable goes out of scope, the next iteration starts and then cube is introduced to the scope again. Logically, there is no clash because no two identifiers cube exist in the same scope - in fact, there is only a single declaration of cube.

It might be worth distinguishing between the declaration of a variable and the creation of an object due to that declaration. There is only one declaration int cube = ...;. It doesn't matter that this piece of code may be reached many times; it's still only one declaration. The rules of the language say that you cannot declare two variables with the same name in the same scope, but that's okay since you're only declaring it once. This is a completely static rule that your compiler is able to analyse.

It just so happens that your declaration is reached 10 times because of your for loop, which means that 10 int objects will be created. Due to the scope of the variable, they won't all exist at the same time. This is not a static property of the program. The compiler cannot in general know beforehand how many times a line of code will be reached.

Upvotes: 15

Biffen
Biffen

Reputation: 6354

The variable will be declared in each iteration of the loop, and then it will go out of scope as the block ({...}) ends, i.e. it will cease to exist. Then on the next iteration it will be declared again, which is not a redeclaration, since it didn't exist. It is said to be a "local variable", in this case local to the block.

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70989

As cube is defined inside the cycle body its scope will be that body. So after each iteration completes cube will go out of scope and on the next iteration a brand new cube will be created. This is what happens in theory. It may happen though that the compiler optimizes this code and only ever creates one variable. Either way the code is perfectly valid and will work as excepted.

Upvotes: 1

JBL
JBL

Reputation: 12907

You've discovered "Automatic-storage duration".

The variable cube is declared inside the loop. Especially, inside the block-scope of the loop. At the end of the loop, this variable will be destroyed, just like any variable declared in any block-scope, be it a function, a loop, an if/else block, or just a raw block scope that you can declare anywhere in the code using { and }, i.e.:

int main(){

    //Beginning of block
    {
        int cube = 1;
        //cube exists and is declared here
    }//End of block

    //cube is gone here

    return 0;
}

So in fact, every iteration of the loop will have its brand new and fresh cube variable.

Upvotes: 6

doctorlove
doctorlove

Reputation: 19272

When you enter the loop a 2nd time, the first cube has gone out of scope so it's all OK.

Two cubes in the same scope would be a problem:

{
    int cube = 0;
    int cube = 1;
}

Upvotes: 8

Related Questions