Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. A question of indentation!

A question of indentation!

Scheduled Pinned Locked Moved The Lounge
questionc++helptutorial
81 Posts 23 Posters 64 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Nish Nishant

    Christian Graus wrote: Try/Thow/catch ( and finally in C#, dunno about C++ ) are the obvious way to deal with your situation. I don't even know how to implement exceptions :-( Might have to do some reading Actually after reading all the suggestions, I liked peterchens do{} while(0) idea :-) Nish


    Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

    J Offline
    J Offline
    Jason Henderson
    wrote on last edited by
    #44

    // Bad example, but it shows you how to use them
    for (int count=0; count<10; count++)
    {
    try
    {
    if (count%2 == 0)
    throw "Even";
    else
    throw "Odd";
    }
    catch(LPSTR str)
    {
    MessageBox(NULL, str, "This number is:", MB_OK);
    }
    catch(...) // all other errors
    {
    MessageBox(NULL, "Unhandled exception.", "Error", MB_OK);
    }
    }

    Like it or not, I'm right.

    E 1 Reply Last reply
    0
    • C Christian Graus

      To quote Stroustrup: The Exception handling mechanism is a nonlocal control structure based on stack unwinding that can be seen as an alternative return mechanism. There are therefore legitimate uses of exceptions that have nothing to do with errors. Christian I am completely intolerant of stupidity. Stupidity is, of course, anything that doesn't conform to my way of thinking. - Jamie Hale - 29/05/2002

      E Offline
      E Offline
      Eddie Velasquez
      wrote on last edited by
      #45

      Christian Graus wrote: There are therefore legitimate uses of exceptions that have nothing to do with errors. Well, I can't pretend to teach C++ to Bjarne! :-O But as quoted, these "legitimate uses that have nothing to do with errors" are the exception, not the rule. (pun intended!) I'm not really thinking about this too hard, but I fail to come up with a case where I would raise an exception that doesn't somehow indicate an error condition. :confused:


      Eddie Velasquez: A Squeezed Devil
      Checkout General Guidelines for C# Class Implementation

      T C 2 Replies Last reply
      0
      • J Jason Henderson

        // Bad example, but it shows you how to use them
        for (int count=0; count<10; count++)
        {
        try
        {
        if (count%2 == 0)
        throw "Even";
        else
        throw "Odd";
        }
        catch(LPSTR str)
        {
        MessageBox(NULL, str, "This number is:", MB_OK);
        }
        catch(...) // all other errors
        {
        MessageBox(NULL, "Unhandled exception.", "Error", MB_OK);
        }
        }

        Like it or not, I'm right.

        E Offline
        E Offline
        Eddie Velasquez
        wrote on last edited by
        #46

        I want to add that it's a bad idea to throw exceptions for anything that doesn't indicate an "exceptional" (uncommon, erroneous) condition because in C++ exception support has a lot of overhead that's too costly for idioms that can be expressed in a cleaner and more efficient way using othe language constructs. Jason Henderson wrote: catch(...) // all other errors { MessageBox(NULL, "Unhandled exception.", "Error", MB_OK); } Just nitpicking... the message should be "unexpected exception" not "unhandled exception" because you just handled the exception!


        Eddie Velasquez: A Squeezed Devil
        Checkout General Guidelines for C# Class Implementation

        1 Reply Last reply
        0
        • J Jason Henderson

          I never thought of it this way but try/catch would be a good "control structure" to use instead of nested if's. Its also 100x easier to read. Is Stroustrup trying to say it should only be used as a return mechanism if it isn't used in error handling? Like it or not, I'm right.

          E Offline
          E Offline
          Eddie Velasquez
          wrote on last edited by
          #47

          Jason Henderson wrote: I never thought of it this way but try/catch would be a good "control structure" to use instead of nested if's. Its also 100x easier to read. The problem is that for most implementations, exception support has too much overhead for practical use as a "control structure" that's not directly related to exceptional (uncommon, errroneous) conditions. Check out Vishal Kochhar's excellent How a C++ compiler implements exception handling article for more information.


          Eddie Velasquez: A Squeezed Devil
          Checkout General Guidelines for C# Class Implementation

          1 Reply Last reply
          0
          • T Tomasz Sowinski

            Eddie Velasquez wrote: I fail to come up with a case where I would raise an exception that doesn't somehow indicate an error condition Assume that you have a dozen of functions searching for some data in smart card, registry, current directory, directories listed in some env variable, etc, etc. So instead of nested constructs like this...

            if (!SearchForFooInGoo(...))
            {
            if (!SearchForFooInBoo(...))
            {
            }
            }

            ... you just throw FooFoundException when one of the calls returns true. Then your exception handler does the job. Perverse, but still possible :-D Tomasz Sowinski -- http://www.shooltz.com

            - It's for protection
            - Protection from what? Zee Germans?

            E Offline
            E Offline
            Eddie Velasquez
            wrote on last edited by
            #48

            Yeah I thought about this but I think it's a bad idea. Check out my reasons why this use of exceptions is a bad idea post


            Eddie Velasquez: A Squeezed Devil
            Checkout General Guidelines for C# Class Implementation

            T 1 Reply Last reply
            0
            • E Eddie Velasquez

              Christian Graus wrote: There are therefore legitimate uses of exceptions that have nothing to do with errors. Well, I can't pretend to teach C++ to Bjarne! :-O But as quoted, these "legitimate uses that have nothing to do with errors" are the exception, not the rule. (pun intended!) I'm not really thinking about this too hard, but I fail to come up with a case where I would raise an exception that doesn't somehow indicate an error condition. :confused:


              Eddie Velasquez: A Squeezed Devil
              Checkout General Guidelines for C# Class Implementation

              T Offline
              T Offline
              Tomasz Sowinski
              wrote on last edited by
              #49

              Eddie Velasquez wrote: I fail to come up with a case where I would raise an exception that doesn't somehow indicate an error condition Assume that you have a dozen of functions searching for some data in smart card, registry, current directory, directories listed in some env variable, etc, etc. So instead of nested constructs like this...

              if (!SearchForFooInGoo(...))
              {
              if (!SearchForFooInBoo(...))
              {
              }
              }

              ... you just throw FooFoundException when one of the calls returns true. Then your exception handler does the job. Perverse, but still possible :-D Tomasz Sowinski -- http://www.shooltz.com

              - It's for protection
              - Protection from what? Zee Germans?

              E 1 Reply Last reply
              0
              • N Nish Nishant

                Indentation is nice. In fact code that is not indented is an absolute pain to even look at. But then sometimes you get into absurd levels of indentation. Right now I am working with the PGP SDK. For certain operations I need to call about 7-10 functions sequentially. The problem is that each of these functions can be called ONLY if all the previous functions are successful. Thus I have something like this.

                if(call1())
                {
                if(call2())
                {
                if(call3())
                {
                if(call4())
                {
                if((call5())
                {
                if(call6())
                {

                That's just a sample, just the tip of the large iceberg. Often it get's a LOT more deeply nested than I have shown above! In such situations can we actually do away with indentation at least partially? For example would it be considered okay to do this.

                if(call1())
                {
                if(call2())
                {
                if(call3())
                {
                if(call4())
                {
                if((call5())
                {
                if(call6())
                {

                I have maintained a little indentation, but it's not perfectly done! Your comments are welcome


                Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                J Offline
                J Offline
                Jason Hooper
                wrote on last edited by
                #50

                Nish - Native CPian wrote: In fact code that is not indented is an absolute pain to even look at. But then sometimes you get into absurd levels of indentation Try generating HTML tables with perl's CGI.pm. (Yes I'm using the MDE to edit perl files... this was before I learned vi) - Jason (SonorkID 100.611) In the beginning, teachers taught the 5 W's: who, what, where, when, why. Now it's just a big damn G

                1 Reply Last reply
                0
                • E Eddie Velasquez

                  Yeah I thought about this but I think it's a bad idea. Check out my reasons why this use of exceptions is a bad idea post


                  Eddie Velasquez: A Squeezed Devil
                  Checkout General Guidelines for C# Class Implementation

                  T Offline
                  T Offline
                  Tomasz Sowinski
                  wrote on last edited by
                  #51

                  I don't buy performance-related arguments, at least not in 100%. While there are the situations in which this could matter (thight loops etc), in my example you'd access disk. For sure this operation would be orders of magnitude slower than throwing/catching exceptions. The same applies to displaying anything on the screen or accepting user input. In short, the cost associated with exception handling would be totally invisible. Tomasz Sowinski -- http://www.shooltz.com

                  - It's for protection
                  - Protection from what? Zee Germans?

                  E 1 Reply Last reply
                  0
                  • J Jason Gerard

                    Nish - Native CPian wrote: PGP calls return a PGPError and you need to call IsPGPError(...) on it to figure out whether it was an error or not. That is the worst API I've ever heard of. Jason Gerard

                    A Offline
                    A Offline
                    Andreas Saurwein
                    wrote on last edited by
                    #52

                    Jason Gerard wrote: That is the worst API I've ever heard of Try Windows ;) ERROR_MORE_DATA Well, actually you have the same kind of return values in almost any API - commonly you find this things in "evolved" API's where conditions changed but not the environment. Thus, the function returns a error which must be interpreted to find out that its actually just a information. Sometimes its just a misconception as for ERROR_MORE_DATA. Vote against software patents in europe

                    1 Reply Last reply
                    0
                    • C Chris Maunder

                      do {
                      if (!call1())
                      break;
                      if (!call2())
                      break;
                      ...
                      } while (false);

                      Cleanup();

                      cheers, Chris Maunder

                      VC++ - the language that doesn't say 'no'

                      T Offline
                      T Offline
                      Tomasz Sowinski
                      wrote on last edited by
                      #53

                      What about this? :)

                      switch (1)
                      {
                      case 1: if (!call1()) break;
                      case 2: if (!call2()) break;
                      case 3: if (!call3()) break;
                      ...
                      }

                      Tomasz Sowinski -- http://www.shooltz.com

                      - It's for protection
                      - Protection from what? Zee Germans?

                      N 1 Reply Last reply
                      0
                      • E Eddie Velasquez

                        (Using my best Yoda voice...) Ummm. Strong in the force you are... but OOP you must.;)


                        Eddie Velasquez: A Squeezed Devil
                        Checkout General Guidelines for C# Class Implementation

                        N Offline
                        N Offline
                        Nish Nishant
                        wrote on last edited by
                        #54

                        Eddie Velasquez wrote: but OOP you must. Yeah. I am gonna OOP more from now on ... Nish :-)


                        Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                        1 Reply Last reply
                        0
                        • C Chris Maunder

                          do {
                          if (!call1())
                          break;
                          if (!call2())
                          break;
                          ...
                          } while (false);

                          Cleanup();

                          cheers, Chris Maunder

                          VC++ - the language that doesn't say 'no'

                          N Offline
                          N Offline
                          Nish Nishant
                          wrote on last edited by
                          #55

                          Thanks Chris M. PeterChen had already suggested this to me. Though he used a 0 instead of a false as you did :-) By the way your do while brace-poitioning is ugly Dont use do { like a java guy. Put it as do { like a C++ guy Nish


                          Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                          1 Reply Last reply
                          0
                          • T Tomasz Sowinski

                            What about this? :)

                            switch (1)
                            {
                            case 1: if (!call1()) break;
                            case 2: if (!call2()) break;
                            case 3: if (!call3()) break;
                            ...
                            }

                            Tomasz Sowinski -- http://www.shooltz.com

                            - It's for protection
                            - Protection from what? Zee Germans?

                            N Offline
                            N Offline
                            Nish Nishant
                            wrote on last edited by
                            #56

                            That was indeed innovative Tomasz :-) Nish


                            Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                            1 Reply Last reply
                            0
                            • T Tomasz Sowinski

                              I don't buy performance-related arguments, at least not in 100%. While there are the situations in which this could matter (thight loops etc), in my example you'd access disk. For sure this operation would be orders of magnitude slower than throwing/catching exceptions. The same applies to displaying anything on the screen or accepting user input. In short, the cost associated with exception handling would be totally invisible. Tomasz Sowinski -- http://www.shooltz.com

                              - It's for protection
                              - Protection from what? Zee Germans?

                              E Offline
                              E Offline
                              Eddie Velasquez
                              wrote on last edited by
                              #57

                              Tomasz Sowinski wrote: While there are the situations in which this could matter (thight loops etc), in my example you'd access disk As everything in software development there's no such thing as an absolute certainty. That's why I used the word "usually". And I still believe it's a bad idea to getting used to use exceptions for other things besides error handling. Tomasz Sowinski wrote: In short, the cost associated with exception handling would be totally invisible. Remember the cost of exceptions isn't only related to speed, size matters too! (Doesn't matter what some women say :-O ;))


                              Eddie Velasquez: A Squeezed Devil
                              Checkout General Guidelines for C# Class Implementation

                              T 1 Reply Last reply
                              0
                              • T Tomasz Sowinski

                                Post more code - especially, how PGPError is returned and when it means an error. Tomasz Sowinski -- http://www.shooltz.com

                                - It's for protection
                                - Protection from what? Zee Germans?

                                N Offline
                                N Offline
                                Nish Nishant
                                wrote on last edited by
                                #58

                                Tomasz Sowinski wrote: Post more code Tomasz Sowinski said that on the Lounge ;-) ;-) Nish


                                Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                                T 1 Reply Last reply
                                0
                                • J James Pullicino

                                  Nish - Native CPian wrote: Shucks! It always comes down to the basics and theory. If my OOP theory was strong enough I'd not have run into this situation Nish, don't get discouraged. The prime motivation for most of us to learn OOP was because of these things. Don't shy away from OOP. In a few months you will be the one telling others to wrap their functions into objects. C++ Programmers do it in class Drinking In The Sun Forgot Password?

                                  N Offline
                                  N Offline
                                  Nish Nishant
                                  wrote on last edited by
                                  #59

                                  [James Pullicino] wrote: Nish, don't get discouraged. The prime motivation for most of us to learn OOP was because of these things. Don't shy away from OOP. In a few months you will be the one telling others to wrap their functions into objects. Thanks James! :-) Nish


                                  Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                                  1 Reply Last reply
                                  0
                                  • N Navin

                                    Nish - Native CPian wrote: if (call1() && call2() && call3() ....) That won;'t work. I am not supposed to call call-n unless call-n-1 returns true! :confused: Why won't that work then? With C++, you have "short-circuit" evaluation - that is, if the first item in an If statement fails, the rest won't even get evaluated. For instance, I have code like this all the time (well, when I'm not using CStrings... :-D) : if(pStr != NULL && strlen(pStr) > 0) { ... } If pStr is NULL, the first condition fails, and the second condition (strlen) won't even be evaluated. No generalization is 100% true. Not even this one.

                                    N Offline
                                    N Offline
                                    Nish Nishant
                                    wrote on last edited by
                                    #60

                                    Navin wrote: If pStr is NULL, the first condition fails, and the second condition (strlen) won't even be evaluated. PGP calls don't return true/false/1/0. They return a PGPError type. We gotta call IsPGPError() on the return value to figure out if it's an error. On some occasions an error is permissible. Like if we have a call that works only with DSS keys, then if it fails for an RSA key it's not really an error. Nish


                                    Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                                    1 Reply Last reply
                                    0
                                    • N Nish Nishant

                                      Eddie Velasquez wrote: if(!call3()) return; I can't do that. Since I need to do some cleaning up as well :( Nish


                                      Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                                      J Offline
                                      J Offline
                                      Jorgen Sigvardsson
                                      wrote on last edited by
                                      #61

                                      Some people use goto :~ for this kind of stuff. Basically it works something like this:

                                      if(someCondition) {
                                         // acquire some resources...
                                         // some error is detected - bail out
                                         goto cleanup\_1;
                                      }
                                      
                                      if(someOtherCondition) {
                                         // acquire some more resources...
                                         // some error is detected - bail out
                                         goto cleanup\_2;
                                      } 
                                      
                                      // perhaps some more code
                                      
                                      return true; // for success
                                      

                                      cleanup_2:
                                      // cleanup resources acquired up to "goto cleanup_2"
                                      cleanup_1:
                                      // cleanup resources acquired up to "goto cleanup_1"
                                      return false; // for failure

                                      This is the only instance where I'm prepared to defend the usage of goto's. It's fast (no exception handling overhead), it's not spaghetti code and it's quite readable! Sonorked as well: 100.13197 jorgen FreeBSD is sexy.

                                      1 Reply Last reply
                                      0
                                      • E Eddie Velasquez

                                        Tomasz Sowinski wrote: While there are the situations in which this could matter (thight loops etc), in my example you'd access disk As everything in software development there's no such thing as an absolute certainty. That's why I used the word "usually". And I still believe it's a bad idea to getting used to use exceptions for other things besides error handling. Tomasz Sowinski wrote: In short, the cost associated with exception handling would be totally invisible. Remember the cost of exceptions isn't only related to speed, size matters too! (Doesn't matter what some women say :-O ;))


                                        Eddie Velasquez: A Squeezed Devil
                                        Checkout General Guidelines for C# Class Implementation

                                        T Offline
                                        T Offline
                                        Tomasz Sowinski
                                        wrote on last edited by
                                        #62

                                        Eddie Velasquez wrote: Remember the cost of exceptions isn't only related to speed, size matters too! So how much bigger my program will be if I replace multiple nested ifs with try/throw/catch? Assuming that you're using exceptions to catch 'real' errors the difference is zero. Tomasz Sowinski -- http://www.shooltz.com

                                        - It's for protection
                                        - Protection from what? Zee Germans?

                                        E 1 Reply Last reply
                                        0
                                        • N Nish Nishant

                                          peterchen wrote: do { // while(0) ok = hamlet(); if (!ok) break; ok = ophelia(); if (!ok) break; ....} while(0); Cool! I like your do while(0) idea. That's what I am gonna use I think :-) Nish


                                          Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                                          J Offline
                                          J Offline
                                          Jorgen Sigvardsson
                                          wrote on last edited by
                                          #63

                                          Nish - Native CPian wrote: I like your do while(0) idea do { } while(0) is a really cool technique, especially with macros. It is easy to mistype macros in such ways that they look syntactically correct, but expanded they wreak havoc. Consider this:

                                          #define RET_IF_FAIL(x) if(FAILED(x)) return

                                          if(someCondition)
                                          RET_IF_FAIL(m_pObject->DoTheChokaChoka());
                                          else
                                          MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                                          The else will be connected to your "hidden if" inside RET_IF_FAIL which is clearly not the intent. The expanded code will look like:

                                          if(someCondition)
                                          if(FAILED(m_pObject->DoTheChokaChoka())) return;
                                          else
                                          MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                                          Scary stuff! I've had my fair share of these bloody mistakes! Solution? Keep on reading:

                                          #define RET_IF_FAIL(x) do { if(FAILED(hr)) return; } while(0)
                                          if(someCondition)
                                          RET_IF_FAIL(pObject->DoTheChokaChoka());
                                          else
                                          MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                                          This is much better since the "hidden if" is wrapped inside a block which has an associated language construct - the do while. Thus the if nor the block cannot be "misconnected". The expanded code will be:

                                          if(someCondition)
                                          do { if(FAILED(m_pObject->DoTheChokaChoka())) return; } while(0);
                                          else
                                          MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                                          And the best part is that a do { } while(0) is totally costless! The compiler will optimize away the loop expression/jump so that it will not add any extra garbage to your code. Sonorked as well: 100.13197 jorgen FreeBSD is sexy.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups