Home > Software engineering >  Why can't I declare this variable within while loops?
Why can't I declare this variable within while loops?

Time:01-24

I am VERY new to programming, so forgive me if this question seems a bit stupid, but why is it that when I try to run this code it doesn't work:

    int calculate_quarters(int cents)
{
    while((25 <= cents) && (cents < 50))
    {
        int quarters = 1;
    }
    while((50 <= cents) && (cents < 100))
    {
        int quarters = 2;
     }
     return quarters;
}

But when I try to run this code it works perfectly well?

 int calculate_quarters(int cents)
{
    int quarters = 0;
    while((25 <= cents) && (cents < 50))
    {
        quarters = 1;
    }
    while((50 <= cents) && (cents < 100))
    {
        quarters = 2;
     }
     return quarters;
}

CodePudding user response:

To see what @hyde means even better, imagine you collapse the loops. Than in the first example the variable literally becomes invisible so you cannot return it.

CodePudding user response:

Here's a visual picture of your situation:

enter image description here

For your first code, quarters is declared inside a while loop, so it cannot be referenced from an outside scope.

However, for your second code, quarters is declared within the method, so it can now be referenced within that scope.

CodePudding user response:

Variables are in scope in the block they are declared in. Their lifetime ends at the end of the block.

So in the first example, your two quarters variables are completely separate variables, which co-incidentally have same name. Both disappear at the end of the block, in this case they are created and destroyed every loop iteration.


Here is example code which demonstrates this by creating local variable with custom class, which prints stuff in constructor and in destructor

#include <iostream>

struct Print {
    Print(int value) : value(value) { std::cout << "Constructor_" << value << "\n"; }
    ~Print()  { std::cout << "Destructor_" << value << "\n"; }
    int value;
};

int main()
{
    std::cout << "Starting loop...\n";
    for(int cents = 0; cents < 10;   cents) {
        Print object(cents);
    }
    std::cout << "DONE.\n";

}

Output:

Starting loop...
Constructor_0
Destructor_0
Constructor_1
Destructor_1
Constructor_2
Destructor_2
Constructor_3
Destructor_3
Constructor_4
Destructor_4
DONE.
  •  Tags:  
  • Related