Break and Continue 10-10-2017, 07:37 AM
#1
This one was suggested by @Mr.Kurd based on my short tutorial about for loops.
So, what do the keywords break and continue do, and how do they work?
Let's take a look at an infinite wait loop:
Ok, so this is a pretty basic example, the loop runs until flag gets set. Do not confuse this with a while(flag); loop, it's not the same.
Basically, what happens is that whenever a break is encountered, it will jump up exactly one level in a loop.
Continue works in the same sort of way. You'll understand it a little bit better once you look at the code for this one.
Let's say, we want a while loop that will initialize itself (for some reason):
Now, this could act like a memory manager, garbage collector, whatever. It's only job is to constantly monitor val and make sure that it exists. If it got deleted, it recreates it again. Once flag is set (like in the event that the child thread is done), the loop exits.
You can also use break as an error check within loops. For example, here's a while loop that will find the end of your linked list:
I know this one was even shorter, these are basic concepts. Maybe I'll keep writing these small ones out and eventually compile them into some form of SL book. Let me know what your questions are.
So, what do the keywords break and continue do, and how do they work?
Let's take a look at an infinite wait loop:
Code:
bool flag;
flag = false; //this will be set to true by another thread
while (true)
{
if (flag)
break; // exit the loop
}
Basically, what happens is that whenever a break is encountered, it will jump up exactly one level in a loop.
Continue works in the same sort of way. You'll understand it a little bit better once you look at the code for this one.
Let's say, we want a while loop that will initialize itself (for some reason):
Code:
int *val;
bool flag;
val = NULL;
flag = false;
while (true) // indefinite thread loop
{
if (val == NULL) // it's not allocated
continue; // jump back up so we don't use val until the thread allocates it
*val = 5; // set it to something, or do some calculation on it
if (flag)
break;
}
You can also use break as an error check within loops. For example, here's a while loop that will find the end of your linked list:
Code:
struct llist *result;
result = <input list>;
while ((result = result->next) != NULL)
if (result->next == NULL)
break; // result is now the end of the list
I know this one was even shorter, these are basic concepts. Maybe I'll keep writing these small ones out and eventually compile them into some form of SL book. Let me know what your questions are.