Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

C++ syntax, nested loops and continue — an embarrassing experiment?

Posted by peeterjoot on August 28, 2012

For whatever reason, the C++ continue keyword is not used often in the portions of the code I normally deal with.  I was moving code in a function that had gotten waaay to big into a helper function. This changed the scope of some continue and break usage, and thought I’d double check that these only impact the inner loop:

#include <stdio.h>

int main()
{
   for ( int i = 0 ; i < 5 ; i++ )
   {
      for ( int j = 0 ; j < 5 ; j++ )
      {
         if ( j % 2 )
         {
            continue ;
         }

         printf( "i,j = %d, %d\n", i, j ) ;
      }
   }

   printf( "\n\n" ) ;
   for ( int i = 0 ; i < 5 ; i++ )
   {
      for ( int j = 0 ; j < 5 ; j++ )
      {
         if ( 3 == j )
         {
            break ;
         }

         printf( "i,j = %d, %d\n", i, j ) ;
      }
   }

   return 0 ;
}

I see:

i,0 = 0, 0
i,2 = 0, 2
i,4 = 0, 4
i,0 = 1, 0
i,2 = 1, 2
i,4 = 1, 4
i,0 = 2, 0
i,2 = 2, 2
i,4 = 2, 4
i,0 = 3, 0
i,2 = 3, 2
i,4 = 3, 4
i,0 = 4, 0
i,2 = 4, 2
i,4 = 4, 4


i,0 = 0, 0
i,1 = 0, 1
i,2 = 0, 2
i,0 = 1, 0
i,1 = 1, 1
i,2 = 1, 2
i,0 = 2, 0
i,1 = 2, 1
i,2 = 2, 2
i,0 = 3, 0
i,1 = 3, 1
i,2 = 3, 2
i,0 = 4, 0
i,1 = 4, 1
i,2 = 4, 2

This makes logical sense, and protects me from breaking code containing the inner loop in question should I move it to a helper function (where there will no longer be an outer loop in scope).

Should it be embarrassing that I actually did this experiment after so many years of programming?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: