Mr.Nutty's Palace

Blog

A conversation about the use of 'break' in a loop [C++]

Posted by D.Chhetri on January 31, 2012 at 9:25 PM

So today, one of my friend asked me about the use of break in a for loop? He wanted to know whether to using break in a for loop if a good idea or not? Well let see...


Here is a typical code where one has a chance to use break( assume there isn't a library function for this )

1.)  int find(int target, const int * array, const size_t size){
2.)    int index = -1;
3.)    for(int i = 0; i < size; ++i){
4.)      if(array[i] == target){
5.)          index = i;
6.)          break;
7.)      }
8.)    }

9.)   return index;
10) }

 

Is the above readable and clear? Yes. That is because the function can be described in plain english. Here is one way to read the function:

  'find' is a function that takes a target value to find from a array which will not be changed or altered. It tries to find the target value by looping through the whole array until there is a match with the current array value with the target, and if there is a match, then we save the current index and break out of the loop, else we keep chugging through until the end of the array. If at the end of the array we do not find the target value, we return the variable index which was initialized to negative one and never changed.


Ok thats clear enough, but can it be done another way that doesn't use break? Why yes of course. Here is an example.

1.)  int find(int target, const int *array, const size_t size){
2.)   int index = -1;
3.)   bool found = false;
4.)   for(int i = 0; i < size && !found; ++i){
5.)       if(array[i] == target){
6.)          index = i;
7.)          found = true;
8.)       }
9.)   }

10.)  return index;
11.) }


Using a similar way of reading style, this too can also be read easily. But is this a better version that the pervious one? I don't know, what's your definition of better? But as for my opinion, I like option 1 better. Why? Well for the following reasons:

  • Option 1 does not use an extra boolean variable
  • Option 1 does not use a extra check on the for loop ( i.e doesn't use "!found" extra boolean check)
  • Option 1 follows the rule of using a variable in the tightest scope by simply not using a variable and using the keyword break in place of the variable :)
  • I've always used option 1 since I started programming so I'm biased, plus less typing lol

One could say there is still a way to not use break, and the boolean variable and instead just return when needed. This is ok, but however is not viable in the general case. For example, there might be a time where you don't want to return from the loop but simply break out of it.

Also note, that sometimes using break is not viable to break out of a loop, for example in the situation where you want to break out of the whole nested loop from the inner most loop, you cannot use a break statement( you could but it wont do the job you want). Instead a good way to break out of a nested loop from the inner most loop is to use a boolean variable.


But here is the deal, it all comes down to style. If you have been using one way and it has worked, then there is no need to change your style, unless there is a compelling reason to do so. For example, if your company uses style X and you use style Y, then my advice would be to use style X and keep it consistent. It all comes down to style and consistency. If you are consistent with your style and if its correct, then don't worry about other approaches for now, just keep coding. However, this does not rule out the drive to write better code. If someone shows you a better way to do it and proves that it is better without a doubt, then you might want to give that option a try as well. Hope you enjoyed the small talk! Be safe and take care!

reagards, MrNutty

Categories: None

Post a Comment

Oops!

Oops, you forgot something.

Oops!

The words you entered did not match the given text. Please try again.

Already a member? Sign In

6 Comments

Reply Saradhi
2:45 AM on February 1, 2012 
1.) int find(int target, const int *array, const size_t size){
2.) int index = -1;
3.) bool found = false;
4.) for(int i = 0; i
Reply ch
5:06 AM on February 1, 2012 
How about:
1.) int find(int target, const int * array, const size_t size){
2.) for(int i = 0; i
Reply Steve
6:03 AM on February 1, 2012 
I'd even go further. In some rare cases, I'll throw an exception for success ("My God! I actually found it!") as an easy way of "breaking" out of nested loops, or (more likely) out of some unknown depth of recursive search.

My excuse is that compared with all the "I didn't find that here, better look elsewhere" and "I've got nowhere left to look - I give up, lets backtrack" actually finding something really is, in some cases, exceptional.
Reply Jerome
6:04 AM on February 1, 2012 
Sorry, both your examples are ugly. The first because it uses a variable which brings nothing to readability, the second because it uses 2 variables which bring nothing to readability. The code should be:

1.) int find(int target, const int *array, const size_t size){
2.) for(int i = 0; i
Reply eZanmoto
6:54 AM on February 1, 2012 
This would be my most efficient example, it uses only one variable (the iterator), two comparisons on each loop and is quite short. The last line isn't very readable though, but this can be abstracted into an intention-revealing function, say, in_range( i, range ), which returns i if the variable is in range, and -1 otherwise. Anyway, the code:

[sourcecode language="c"]
1.) int find(int target, const int *array, const size_t size){
2.) int index = 0;
3.) while(index
Reply eZanmoto
7:02 AM on February 1, 2012 
It seems everyone's post is getting truncated, so I've put my solution here: https://gist.github.com/1716744