Let's analyze your question step-by-step.
The question:
Can this work? Can I repeatedly declare a variable?
You posted 3 very similar while loops consecutively, each time declaring:
ReplacementListNode* newNode = new ReplacementListNode{currentMilk, nullptr};
Yes, you can declare variables with the same name multiple times, provided they are in separate scopes. In your case, each declaration of newNode is inside the body of the while loop, which means each iteration creates a new variable newNode local to that iteration's scope.
Why is this legal?
- In C++, each iteration of the
while loop forms a new scope for the variables declared inside it.
newNode is declared inside the loop, so at the end of each iteration, newNode goes out of scope.
- When the next iteration begins, you declare a new
newNode variable local to that iteration.
Could you declare the same variable multiple times sequentially?
You cannot declare two variables with the same name in the same scope consecutively without any scope separation:
int a = 5;
int a = 6; // ERROR: redefinition of 'a'
But inside the loop, multiple declarations over multiple iterations are perfectly fine.
In your specific code snippet:
You have three entire while loops written one after another, all checking currentMilk != nullptr and in each loop doing the same thing:
while (currentMilk != nullptr) {
ReplacementListNode* newNode = new ReplacementListNode{currentMilk, nullptr};
// ...
currentMilk = currentMilk->next;
}
Technically, this is legal code but practically:
- Once the first
while loop finishes, currentMilk is already nullptr.
- So the second and third loops do nothing because the condition fails immediately.
- Repeating the entire loop three times in a row is unnecessary and probably a mistake or copy-paste error.
Summary:
- You can declare
ReplacementListNode* newNode inside the while loop — each iteration has its own newNode.
- You can have multiple loops with the same code, but usually, only the first one will run if they use the same condition and advance the same pointer.
- Declaring variables with the same name in different scopes or iterations is allowed.
- Declaring variables twice with the same name in the same scope without scope separation is not allowed.
Possible improvement
If your goal is to build a list copying elements pointed to by currentMilk, you only need one while loop:
while (currentMilk != nullptr) {
ReplacementListNode* newNode = new ReplacementListNode{currentMilk, nullptr};
if (tempList == nullptr) {
tempList = newNode;
curr = newNode;
} else {
curr->next = newNode;
curr = newNode;
}
currentMilk = currentMilk->next;
}
No reason to repeat this whole loop multiple times.
If you want me to help clean up the code or explain a detail further, feel free to ask!