Thread: Which one of these if() statements is best?...

  1. #1
    Registered User MathFan's Avatar
    Join Date
    Apr 2002
    Posts
    190

    Which one of these if() statements is best?...

    Hi,

    I am wondering which one of these is better to use in my code:

    Code:
    //this one:
    
    void handleMouseClick(const int X, const int Y)
    {
    	if(SelectedObject==NULL)
    		return;
    		
    	SelectedObject->Move(X, Y);
    	SelectedObject->Update();
    	//...
    }
    
    //or this one:
    
    void handleMouseClick(const int X, const int Y)
    {
    	if(SelectedObject!=NULL)
    		{
    			SelectedObject->Move(X, Y);
    			SelectedObject->Update();
    			//...
    		}
    }
    They do the same thing. So: Is it totally up to me, or does each of these methods have its pros and cons?

    Thanks.
    The OS requirements were Windows Vista Ultimate or better, so we used Linux.

  2. #2
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    From an optimization perspective.. you should stack the deck against the case you think will occur more frequently.. I like the first option because it provides you an opportunity to break out of the function right away and move on to bigger and better things if necessary.
    Last edited by The Brain; 05-05-2005 at 12:18 PM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    It depends on if you really care about having a single return point from your function or not. Having extra returns scattered throughout a function can lead to some missteps during debugging, similar to good ole goto.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    As mentioned it really depends, but generally I prefer the first one. You get less nesting and the program flow is easier to follow. I also like the exclusion paradigm that you do something, return if it fails, do something, return if it fails etc...

    As an example, the classic point-inside-region check, I prefer this way:
    Code:
    bool PointInRegion(Point point, Region region)
    {
      if(point.x <  region.left)   return false;
      if(point.x >= region.right)  return false;
      if(point.y <  region.top)    return false;
      if(point.y >= region.bottom) return false;
    
      return true;
    }
    instead of this:
    Code:
    bool PointInRegion(Point point, Region region)
    {
      return (point.x >= region.left)  &&
             (point.x <  region.right) &&
             (point.y >= region.top)   &&
             (point.y <  region.bottom);
    }
    Last edited by Magos; 05-05-2005 at 08:28 AM.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  5. #5
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    well i personally prefer example 2. Its infinately more readable and concise. Its obvious to any newbie c++ programmer that if the if condition isnt met then the end of the function is reached. A good compiler will generate the same object code for both but the second just looks better.Even with your example magos I still prefer the second example. Ok its not as obvious as mathfans example but again anyone with fair exp. of c++ will be able to read that line with no problem at all and see exactly whats going on.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  6. #6
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    If prefer the first, for the same reasons as Magos. But then, I never bought into the "don't have multiple return positions" rule.


    As you see, it's entirely up to you and the coding standards of your work environment.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  7. #7
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    In all honesty, the only time the "don't have multiple return positions" rule has come in handy for me was in patching up this little bug Microsoft left for us.
    http://ng.csharpfriends.com/top/ng/g...lem/index.aspx
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  8. #8
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    I don't see the bug in this link. C++ boolean values are marshalled as BOOL, not bool. That's annoying if you don't know about it, but probably not a bug as in "oops, made a mistake while coding this".

    I prefer multiple return statements, because it's easier to read and easier to debug. There is nothing worse than coming to a function end with a large expression and having to figure out what it might return.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  9. #9
    Chief Code Coloniser!
    Join Date
    Apr 2005
    Posts
    121
    I'm not a fan of the first to be honest, but this is more to do with cleaning up than anything. If you have a function that allocates some memory temporarily, then you need to make sure that you clean it up before the function exits. In this case you'd end up with not just a bunch of return statements, but with a bunch of clean up statements aswell. eg:
    Code:
    int* x = new int[100];
    // do stuff
    if(!isvalid)
    {
       delete [] x;
       return false;
    }
    
    // do more stuff
    if(!isValid)
    {
       delete [] x;
       return false;
    }
    
    // .. etc.
    Yes, I realise the example is bad, bit it should get the point across

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    That's why you should use RAII, TheColonial:
    Code:
    boost::scoped_array<int> x(new int[100]);
    if(!isvalid) {
      return false;
    }
    // do
    if(!isvalid) {
      return false;
    }
    // do
    if(!isvalid) {
      return false;
    }
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by nvoigt
    I don't see the bug in this link.
    Bah...probably because I posted the wrong link.
    http://groups-beta.google.com/group/...d9c1e3015207f0
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  12. #12
    Chief Code Coloniser!
    Join Date
    Apr 2005
    Posts
    121
    CornedBee: as I said, not the best example, but it does make the point valid. Yes, there are workarounds for that issue (i'm aware of boost and it's contents), but let's say you're building a DirectX game/application, and adding more and more layers of abstraction on top of something like an index/vertex buffer isn't feasible for performance reason, and you're trying to construct a combination of vertex/index buffers in a single function. First bit fails, second bit doesn't, you then have to release before exiting for fear of memory leaks!?

    I'm sure there are arguments either way, at the end of the day, I personally feel that a few levels of nesting make the code easier, and trim down the amount of duplicated code that you may have to write to make sure things are cleaned up.

    Cheers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  2. newbie question - if statements without conditions
    By c_h in forum C++ Programming
    Replies: 2
    Last Post: 07-18-2008, 10:42 AM
  3. C++ If Statements Help
    By moporho in forum C++ Programming
    Replies: 19
    Last Post: 01-18-2008, 08:40 AM
  4. Efficiency of case statements
    By Yasir_Malik in forum C Programming
    Replies: 26
    Last Post: 05-23-2006, 11:36 AM
  5. Need help with "if" statements
    By Harryt123 in forum C Programming
    Replies: 22
    Last Post: 05-14-2006, 08:18 AM