0

As you can see in the following code, I declared my height variable before the do-while loop (on Line 5). Would it have been better -- or even possible -- to perform this step within the loop?

In other words, could I replace Line 9 with int height = get_int(); and delete Line 5?

BTW, this code hasn't been tested, so feel free to point out any errors! :-)

code snippet

(I'm also assuming that posting this code snippet is considered "reasonable" as per policy.)

2 Answers 2

3

Yes and no. Yes, it is possible, and perfectly permissible to declare height inside the do/while loop, but there's a problem. If you only wanted to use height inside the loop, it's fine. But, the height var would cease to exist when the code exits the loop, so you couldn't use it later. It's a matter of variable scope. See my answer at Pset4 Recover not working for a pseudocode explanation of scope.

Declaring the var before the loop as you did above is the correct way to handle this. (But we won't discuss the problem with the while condition. I'll let you work that one out on your own. ;-) )

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Let''s also remember that the var declared inside the loop only persists for the current pass. It will be destroyed at the end of the pass and recreated on the next pass.
    – Cliff B
    Apr 28, 2021 at 21:54
1

Yes. you can declare a variable inside any loop(includes do while loop.lol).But remember the scope of that variable is restricted inside the loop. That is you can't use that variable outside the loop.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .