CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 20

Threaded View

  1. #11
    Join Date
    May 2008
    Posts
    96

    Re: Best and Neatest way to check status in C

    The goto wars started about the time that structured languages appeared on the scene.

    The main reason people hate them today is learned prejudice, but back then it was something along the lines that "gotos subvert structured code". More practically, they encouraged spaghetti code --which at the time was a serious problem (and I've seen some really awful stuff).

    You'll notice, though, that they still exist in modern languages. I wonder why...

    It might be that they actually have practical purpose! Here's a practical example I just coded recently. It replaces std::getline() to handle files with mixed line-ending sequences (LF - unix, CRLF - windows, or CR - mac)
    Code:
    std::string get_line( std::istream& file )
      {
      std::string result;
    
      while (true)
        switch (int c = file.get())
          {
          case '\r': if (file.peek() == '\n')
          case '\n':   file.get();
          case EOF:  goto l_done;
          default:   result += char( c );
          }
      l_done:
    
      return result;
      }
    Sure, I could have made myself a bool named "done" or somesuch and played with it, but why bother? Every time you say break you are using goto in disguise, and considering I gave the compiler enough to think about by mixing switch and if statements there's no cause to add junk just for some misplaced sense of moral superiority.

    Gotos continue to exist in the language because they have their place.

    Whenever anyone starts making always or never statements, he exposes himself as a proto-weenie.
    http://www.parashift.com/c++-faq-lit....html#faq-6.15
    http://www.parashift.com/c++-faq-lit....html#faq-6.16



    In a language like C++, I tend to use exceptions to unwind with status. It is very easy to create your own unique exception type for circumstances such as this.
    Code:
    #include <stdexcept>
     
    class eMyResult: public std::runtime_error
      {
      public:
        enum t_code {me_OK, me_Boo, me_Baz};
        t_code code;
        explicit eMyResult( t_code code ): code( code ), std::runtime_error("eMyResult") { }
      };
    
    ... 
    
    throw eMyResult( eMyResult::me_OK );
    But, again, this isn't always the best solution. Use what is best for the task at hand.

    [edit]
    Oh yeah...
    http://www.parashift.com/c++-faq-lit....html#faq-17.1
    Last edited by Duoas; May 19th, 2008 at 10:53 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured