[c++] replacing "for" with "while" loop
Posted by Temporary_Session_60@reddit | learnprogramming | View on Reddit | 39 comments
I've been trying to replace my "for" loops with "while", but every time I have to create a new variable to keep track of when to stop in the while loop, which makes it clunky when using the variable, and sometimes makes naming variables harder for me. Is there a way to still use variable but a local one for each while loop?
Wolfe244@reddit
Why are you doing this?
Soft-Register5177@reddit
Your teacher probably wants you to understand how loops work under the hood. For loops are just syntactic sugar for while loops anyway, so this exercise helps you see the connection. You can create scope with curly braces to keep your counter variables local if that helps with the naming issue
csabinho@reddit
Of course for loops are just syntactic sugar for while loops, but one month? Do it once, so the students see the difference, and use the appropriate loop for the task afterwards.
coder155ml@reddit
Not the case in python
coder155ml@reddit
I’m being downvoted ? Lol ok
csabinho@reddit
What?
coder155ml@reddit
For loops when called are compiled because they have a known end. While loops are interpreted because they are conditional. This is specific to python run via cython.
w1n5t0nM1k3y@reddit
Why not just use jumps (goto) and conditionals. While loops are syntactic sugar as well.
ChemicalRain5513@reddit
{ int i = 0; startOfLoop: // ... i += 1; if (i < n) { goto startOfLoop; } }
Temporary_Session_60@reddit (OP)
Thanks! I think this is the best solution for the naming issue
Temporary_Session_60@reddit (OP)
My teacher said we have to do this for a month idk why 🥲
RecentlyRezzed@reddit
Perhaps next month will be goto-month. ;)
Wolfe244@reddit
Well, you just gotta make a local variable that's just how while loops work
Feisty_Manager_4105@reddit
If I'm understanding your question right, what you could do is put your while loop enclosed in a function and declare your "count" variable inside the function ( in the stack) so it
void myfunction(){int myCounter = 0;while( condition){myCounter++;}}Temporary_Session_60@reddit (OP)
So for each individual "for" loop will it be another void function?
Standard-Constant585@reddit
How about a macro?
Temporary_Session_60@reddit (OP)
Can you give me an example? I can't think of one
Standard-Constant585@reddit
I wasn’t talking about using any predefined macros. I was simply asking, what if you could write a macro that just wraps your loop in
{}and definesiinside it with a value you provide?It would basically be to save a few keystrokes instead of writing that part manually.
ChaseShiny@reddit
I don't know C++, but don't you need to return myCounter at the end?
Feisty_Manager_4105@reddit
nope. the data type you return is what's specifed before the function name.
Since my function name is myfunction(), void is my return type.
void literally means what it is which is no type, so you return nothing.
if I had
int myfunction ()
then, yes i would have to return an int and that could be myCounter
This isn't specifically for C++ either, a lot of programming languages do this
ChaseShiny@reddit
Thanks for the explanation. If the function doesn't return anything and doesn't change anything outside of itself, it doesn't seem very useful.
Feisty_Manager_4105@reddit
Well, it depends, a function is generally supposed to be code that is reusable.
Your function doesn't neccasray have to return something to be useful.
Maybe you want a function that prints the addition of two numbers given
void myfunction(int a , int b)
{
int sum = a + b;
printf("sum is %d\n", sum);
}
Returning a variable in a function also implies you are creating a variable to store this return value and modify it and sometimes that can be Cumbersome.
In C++ you could instead pass a variable as a reference ( the "&" specifies it is a reference) and then directly modify it within the function bypassing the need for a return/
void myfunction(int& a)
{
a+=5;
}
There's a lot of purposes of void returns so not just limited to above
Miserable_Double2432@reddit
Think this is probably the solution OP’s lecturer is trying to get them to “invent” as it’s a stepping stone towards functional programming.
However, I don’t think you need the function? If I remember correctly C++ has blocks, so you can control scope by just wrapping code in {}. Any variables declared after the opening brace will go out of scope after you leave the block
Feisty_Manager_4105@reddit
Yes, you're right. But I'd use a function since it gives the block a "name" if you will and just makes it readable.
SamuraiGoblin@reddit
A for loop is just a convenient package of a loop.
You can do the same thing with while loop:
To answer your question, no. You can create a variable in the 'for' loop initialisation like this:
But you can't do the same for a while loop. You have to do:
However, you could always wrap it in braces to make the variable local, so you can reuse the same name, but have it mean a different variable:
Rainbows4Blood@reddit
So, the for loop was literally invented as a convenient shortcut to avoid the clunkiness you are describing. So, in reality the way to avoid this problem is to use for loops instead of while. That's what they were invented for.
Why does your teacher want you to do this? Probably to strengthen your mental model of various types of loops.
I would just suck up the clunkiness for that month and go back to using for loops where they make sense afterwards.
miauguau44@reddit
while (0 < 1) { … }
PuzzleMeDo@reddit
It is clunky - that's why we use 'for' loops.
Would adding {} to scope your variables help?
Temporary_Session_60@reddit (OP)
Thanks! It does help a lot with the naming issue and also makes it easier to keep track of each while loop
samanime@reddit
Why are you trying to replace your for loops that need an iterator with a while loop?
You should be using both, and one of the main reasons when you use a for loop is when you need an iterator variable...
Temporary_Session_60@reddit (OP)
My teacher said we have to do this for a month idk why 🥲
Kitchen_Put_3456@reddit
You should ask them why. You really should be learning the why instead of the how. Ask your teacher why there are different kinds of loops and in what situation you should use them. If you want to become a professional programmer you need to also learn the "why?". AI is doing the "how?" part already.
samanime@reddit
Ah, a learning experience. That makes sense then. We do silly things to learn sometimes. :p
As to the answer for your question, no, there isn't really a way to make it nicer in C++.
That said, if you are doing multiple loops, you might consider splitting up your code into smaller functions so you don't have to repeat variable names more often.
You also maybe name them like thingI, thingJ, etc. (if you were looping over something called "thing").
Good luck
Temporary_Session_60@reddit (OP)
Thanks!
divad1196@reddit
In a
for-loopyou would useieverytime I assume? Then think of a way you could declareionce but re-use it/reset it to 0 before each while-loopno_brains101@reddit
The thing you are complaining about? Yeah so... That's literally why we have a
forloop to begin with.BubbleProphylaxis@reddit
the "for" construct is the only one that allows for the creation of a variable in its scope:
for (int i = 0; i < n; i++) { ... } // i exists only within the for loop
otherwise it's this:
int i = 0;
for (i = 0; i < n; i++) { ... }
which is the same as:
int i = 0;
while (i < n) { ... } // iterate maybe 0 times if n <= 0
you can use this as a variant:
int i = 0;
do { ... } while (i < n) // iterate at least once regardless of the condition.
Adelhartinger@reddit
Think about it like this:
A while-loop isn‘t very different from a for-loop, but you don’t out everything on one line. Instead of:
for(start/do until/increment) {}
You can do:
(start) While (do until) {code to do continuously… increment}
TheStonedEdge@reddit
The rule of thumb is
If you know how many iterations are needed in your data set, use a for loop
If you know it's going to be at least once, use a do while loop
If you don't even know if you need to iterate or not then use a while loop