C/C++ loops and macros

In C/C++ you often break from the middle of a loop instead of from the top/bottom. There are arguments against this — it doesn’t respect block structure and it isn’t a functional style. A break is just a goto. But it’s common, easy to understand, and a very useful pattern.

...
    // General loop micro-pattern:
    for ( ; ; ) {
        .. do some stuff ..
        if ( .. test .. ) break;
        .. do some stuff ..
        if ( .. test .. ) break;
        .. do some stuff ..
    }
...
    
// I've seen programmers define LOOP and LOOP_forever macros.
# define LOOP          for(;;)
# define LOOP_forever  for(;;)

...
    LOOP {
        if ( .. ) break;
        .. etc ..
    }
...

You should be careful when defining keyword and structure macros like LOOP — they interfere with editors and other tools and they can hurt readability. But if you like LOOP, you can go further:

// Getting carried away with macros.
# define LOOP             for(;;)
# define LOOP_exit        break
# define LOOP_next        continue
# define LOOP_while( x )  if ( ! x ) break
# define LOOP_until( x )  if ( x ) break

...
    LOOP {
        LOOP_until( test );
        .. do something ..
        LOOP_while( test );
        .. do something ..
        if ( .. ) {
            LOOP_next;
        }
        if ( .. ) {
            .. do something ..
            LOOP_exit;
        }
        .. do something ..
    }
...

Finally, let’s imagine taking the loop macro to the limit. The following isn’t real code so don’t try to compile it.

    // Fantasy loop macro.
    ...
    loop named top_level {
        int how_many_times = 0;
        int my_sum = 0;
        int my_sum2 = 0;
        std::vector<int> my_vector;
        std::stack<int> my_stack;
        ...
        loop {
            for x in { 1, 2, 4, 8 };
            for e in 1..7;
            for y = e * e; /* eval'd each time */
            init g = x * x; /* eval'd once */
            for z = 1 to 10 by 2;
            for a = 10 downto 1;
            for b = 2 inc by 2;
            for c = 2 dec by 2;
            for d = 2 then 6;
            while my_test( );
            until my_test( ) do (is_special = true) exit top_level;
            until my_test( ) exit 2 levels;
            exit;
            next;
            next 2 levels;
            next top_level;
            collect x in my_vector;
            collect x in my_stack push;
            sum x in my_sum;
            reduce x in my_sum2 using plus;
            count my_test( ) in how_many_times;
            if ( ! LOOP_first_time ) {
                std::cout << LOOP_count << std::endl;
            }
            finally {
                std::cout << "leaving loop" << std::endl;
            }
        }
        ...
    }
    ...

Of course this is no longer C/C++ — you can’t do this with #define, you’d have to use a more powerful pre-processor. One that can manipulate code blocks and define nested macros in an enclosing parent. The standard #define macros are not even meant to take blocks as params.

// I've seen this but it may not be portable and I don't recommend it.
# define STANDARD_CATCH( block_ )           \
    try block_                              \
    catch( my::error::warning* w ) {        \
        my::error::log( w);                 \
    }                                       \
    catch ( ... ) {                         \
        my::error::log_unknown( );          \
        throw;                              \
    }

void some_fn( )
{
    .. stuff ..
    STANDARD_CATCH( {
		// Does this macro expand correctly if a comma appears in the block?
        .. stuff ..
    } )
}

Macros like this are usually a bad idea in C/C++, but in Lisp they are common and a very powerful feature of the language. C/C++ has a lot of syntax that communicates structure and keeps the source compact. Lisp has a very simple syntax, which makes it wordy and full of deeply nested parentheses but also makes it easy to extend. Lisp has a programming model that makes it harder to write tight, efficient, close-to-the-metal code, so C and C++ are probably better choices for realtime and systems engineering. But you don’t have to have Lisp to get something like the Lisp macro facility — you could define a pre-processing facility for C/C++ that worked on the block level and added a lot of power. A simpler C++ sytax would help, but it’s not vital.

But this post is getting too long. I’ll talk about what these macros might look like later.

Comments

30 Responses to “C/C++ loops and macros”

  1. pai gow poker on June 26th, 2009 1:05 am

    This blog Is very informative , I am really pleased to post my comment on this blog . It helped me with ocean of knowledge so I really believe you will do much better in the future.

  2. latex-catsuit on March 23rd, 2011 3:02 am

    thanks for your sharing ! it is useful!

  3. http://criminalbackgroundchecked.com/ on July 4th, 2012 12:01 pm

    You actually make it seem so trouble-free with your presentation however I get a hold of this matter to be actually something that
    I think I would never understand. It seems too complex and extremely broad for me.
    I am looking forward for the next post, I will try to discover that the hang
    of it!

  4. link on July 7th, 2012 8:47 am

    This web site is normally a walkthrough
    along the lines of that the info you desired about this and didnt recognize who to ask.
    Glimpse here, and youll definitely discover it.

  5. scholarships for single mothers on July 8th, 2012 3:24 am

    Fine goods from you, man. I have understand your stuff prior to and youre just extremely wonderful.
    I actually along the lines of what youve acquired here,
    certainly along the lines of

  6. scholarships for college students|scholarships for college students in texas|2011 scholarships for college students|scholarships for college students in california|scholarships for college students 2011|easy scholarships for college students|grants and ss on July 8th, 2012 1:45 pm

    You lost me, friend. Figure out real, I imagine I determine what youre saying.
    I am aware what youre saying, nevertheless, you just appear to have forgotten that might be other sorts of folks out of the world who view this challenge for
    which it happens to be and might perhaps not go along with you.
    You might be turning away much individuals who had been lovers of this
    website.

  7. grants for single mothers for college on July 8th, 2012 3:13 pm

    I for example what you guys are up also. Such intelligent work and reporting!
    Carry on that the fine works guys I have incorporated you guys to my blogroll.

    I think itll improve the value of my web site

  8. grants for single parents on July 8th, 2012 3:42 pm

    It looks just like which i have been concerned about my own personal
    info, not necessarily an additional inividual in my little analysis.

  9. cell phone lookup on July 8th, 2012 4:40 pm

    My favorite town out of all Ive been to, has to be Zurich Switzerland.
    Switzerland is one of the best skiing areas. Something I absolutely love, it’s peacefull and comforting.

  10. grants and scholarships for single mothers on July 8th, 2012 4:40 pm

    ibuprofen is mostly a first-rate pain reliever however
    i heard that this one have nasty side effects too

  11. reverse phone lookup on July 9th, 2012 4:32 pm

    Hey very nice site!! Man . Beautiful . Amazing .
    Ill bookmark your website and take the feeds alsoIm happy to look for numerous useful information here in that the post,
    we need develop more strategies in this regard, thanks for sharing.

    . . . . .

  12. cell phone lookup on July 10th, 2012 4:13 am

    It’s good site, I was searching for just like this

  13. white pages cell phone lookup on July 10th, 2012 4:17 am

    This is so great that I had to comment. Im usually just a lurker,
    taking in knowledge and nodding my head in quiet approval at that the first-class stuff.

    this required written props. Theory rocksthanks.

  14. number lookup on July 16th, 2012 12:12 pm

    This is often a topic near to my heart cheers, such as your blog layout too.
    Must be wordpress

  15. reverse phone on July 16th, 2012 12:18 pm

    Friday Night Lights is often a great tv series, i love
    that the game and i love the story

  16. reverse number lookup on July 16th, 2012 12:25 pm

    Hey there! I know this is kind of off topic but I was wondering if
    you knew where I could get a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  17. cell phone number lookup on July 16th, 2012 1:38 pm

    I havent checked in here for a while since I thought it was
    getting boring, but that the last several posts have been good quality so I guess I will add you back
    to my everyday bloglist. You deserve it friend

  18. reverse phone on July 16th, 2012 2:16 pm

    Howdy sir, you have a actually nice blog layout ,

  19. http://www.prlog.org/11734648-criminal-background-check-public-records.html on July 16th, 2012 2:45 pm

    hello!,I just like your writing greatly! share we communicate more about your article on
    AOL I need a specialist on this area to solve my question.
    May be thats you! Hunting forward to see you.

  20. http://www.youtube.com/watch?v=c3-A_ZxBlSQ on July 16th, 2012 4:22 pm

    Wohh just what I was looking for, thanks for putting up.

  21. phone number lookup on July 16th, 2012 5:14 pm

    Right now it appears like Drupal is that the preferred blogging platform available right
    now. out of what Ive read Is that what youre using on your blog

  22. reverse phone directory on July 16th, 2012 7:59 pm

    I love it when people get together and share opinions.

    Great website, continue the good work!

  23. reverse address lookup on July 16th, 2012 8:40 pm

    I would actually love to guest post on your blog.

  24. reverse phone lookup on July 16th, 2012 8:40 pm

    When some one searches for his necessary thing, thus he/she wants to be available that in detail, therefore that thing is
    maintained over here.

  25. http://www.prlog.org/11684341-reverse-cell-phone-lookup-number.html on July 16th, 2012 9:53 pm

    Hello, this weekend is nice in favor of me, as this point in time i
    am reading this enormous informative post here at my home.

  26. http://www.prlog.org/11734633-free-people-search-finder-directory.html on July 17th, 2012 2:10 am

    Whoah this weblog is wonderful i love studying your articles.
    Stay up that the great work! You realize, many individuals are hunting round for this information, you could
    help them very much.

  27. http://ezinearticles.com/?Phone-Number-Search---Stopping-a-Cheater-the-Easy-Way&id=5909547 on July 17th, 2012 2:23 am

    very fine post, i definitely adore this amazing site, persist with it

  28. http://www.prlog.org/11261550-phone-number-lookup-catch-cheater-quickly.html on July 25th, 2012 1:47 am

    I saw something about that subject on TV last night.
    Great post.

  29. how to make money online on July 27th, 2012 6:19 am

    nice one for taking the time to discuss this, I feel strongly about it and love learning
    more on this topic. If feasible, as you gain expertise,
    could you mind updating your website with more info as it can be extremely useful for
    me.

  30. best reverse cell phone lookup on August 20th, 2012 11:28 am

    Nice post. I understand some thing much harder on different websites everyday.
    It will always be stimulating to study content out of other writers and practice a particular thing from
    their site. Id would rather apply certain with all the content on my own weblog whether you dont mind.
    Natually Ill hand over you a link in your web
    blog. Lots of thanks sharing.