|
-
March 9th, 2004, 08:13 AM
#1
Conditions and use of if, elseif or ORed ifs
I want to know which of the following is better and why. Can you please let me know your thoughts? - Thanks
Set one
----------
if (varialbe == something)
{
//identical code
}
if (variable == somethingElse)
{
//identical code
}
Set two
----------
if (varialbe == something)
{
//identical code
}
elseif (varialbe == somethingElse)
{
//identical code
}
endif
Set 3
-------
if (varialbe == something || variable == somethingElse)
{
//identical code
}
// identical code - excatly same line of code in both the conditions
-
March 9th, 2004, 08:20 AM
#2
The third is the best of course.
The first duplicates the code and does the unnecessary second check even if the first succeeded.
The second doesn't do the check, but still duplicates the code.
The third has neither shortcoming.
All the buzzt
CornedBee
-
March 9th, 2004, 08:32 AM
#3
This is what I too know. I was reviewing some code and I need to give actual reasons so as to why third is better over other two.
1) code size less
2) more readable
3) more efficient
Can you let me know others? like time exectuion, binary etc .
Thanks
-
March 9th, 2004, 08:52 AM
#4
Originally posted by mickey
why third is better over other two.
Maintainability!
Imagine you want to change the code that is done in the
//identical code
section. At how many places do you want to change it?
-
March 9th, 2004, 08:21 PM
#5
Of course (due to what may be a type) the code in the first example may actually run twice, where this can not happen in the secondand third.
If that is a typo, then option 3 will typically b the best bet. Remember to put the most likely (if there is one) condition first to get maximum benefit from short circuiting.
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
March 9th, 2004, 08:28 PM
#6
It is going to be optimize anyway...so why not make it readable...2 or 3 are fine though I'd go with the 3...
-
March 10th, 2004, 01:11 AM
#7
Third one is offcourse the best way to go if you have the same code for both the conditions otherwise choose second one. (no endif in C++).
while(true)
cout<<"C++ is divine\n";
Feroz Zahid
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|