Best and Neatest way to check status in C
Hi,
I'm sure this has been discussed before and we all have our own system, but, I am wondering. How do you check status (and stop execution if an error occured) while maintaining the concepts of single exit point and keeping the code clean.
After trying several systems, the one I feel most comfortable with is something like:
Code:
Status f() {
Status ret = SUCCESS;
ret = g1();
if (ret != SUCCESS)
goto bail;
ret = g2();
if (ret != SUCCESS)
goto bail;
...
...
bail:
if (ret != SUCCESS) {
cleanup....
}
return ret;
}
There are pros and cons for every system (the con here is the use of goto, the pro - one cleanup code only and single exit point)
Other possible solutions:
- very very nested ifs (This is called an arrow code because of its shape)
Code:
ret = g1();
if (ret) {
ret = g2();
if (ret) {
...
}
}
- put a return in every failure - many exit points (maybe not that bad?)
Code:
if (!g1())
return;
if (!g2())
return;
- use a loop to surround the function and break when error occurs
Code:
while(1) {
if ( !(ret = g1()) )
break;
if ( !(ret = g2()) )
break;
}
- theres probably alot more.
If there are articles on this issue that i am not aware of I'd be glad to recieve a link.
I'd like to hear suggestions or thoughts about this issue.
Thank you!
Re: Best and Neatest way to check status in C
Using a while loop is the most common.
Using goto is seriously frowned upon in C++.
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by GCDEF
Using goto is seriously frowned upon in C++.
Well, in C++ we have exceptions for this sort of thing. I've seen a lot of C code that uses the goto method, and I can't say it's the worst solution given the limitations of that language.
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by Hermit
Well, in C++ we have exceptions for this sort of thing. I've seen a lot of C code that uses the goto method, and I can't say it's the worst solution given the limitations of that language.
I doubt you'll find many people advocating goto over a loop, but I could be wrong.
Re: Best and Neatest way to check status in C
Well... I admit that the while method is the one to compare to goto because they are kinda the same. The question is, why is goto so frowned upon? (in this case obviously. in the general case goto is indeed evil)
What is the advantage of while over goto ??
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by hesher
The question is, why is goto so frowned upon? (in this case obviously. in the general case goto is indeed evil)
Maybe because it's evil in the general case, and blanket rules make life easier. Treating goto as contraband simpliciter greatly reduces the risk of ever having to debug the most horrific form of spaghetti code.
On the other hand, I feel I can make an exception here. The loop version seems more prone to resulting in an infinite loop, although a mistake of that nature would probably be caught on the first test run. It's also my opinion that the goto version is clearer of intent (more so than a loop that's not intended to loop), but not by much.
I'm not trying to be an advocate of goto here, and if anything I'm advocating C++ and exceptions.
Re: Best and Neatest way to check status in C
Thanks. Good Argument!
I think goto is shaping up to be the lesser of all evils (bare in mind that C++ is a luxury for some of us :) ).
Re: Best and Neatest way to check status in C
Two words Code maintenance.
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by STLDude
Two words Code maintenance.
Is there a method that is optimal for Code Maintenance. I don't think so.
If anything, I think goto is still the most decent solution to offer Code Maintainability.
- It doesn't create more than one exit point (the code logic is easier to follow)
- It doesn't leave allot of indentation or cleanup (the code is easier to read, visually)
- It shares the same disadvantage as all the other solution - It doesn't protect the coder
from himself (a mistake will not be automatically discovered). The only solution that kinda
does that is the "while" one and it has its own disadvantages (as we discussed).
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by hesher
Is there a method that is optimal for Code Maintenance. I don't think so.
If anything, I think goto is still the most decent solution to offer Code Maintainability.
- It doesn't create more than one exit point (the code logic is easier to follow)
- It doesn't leave allot of indentation or cleanup (the code is easier to read, visually)
- It shares the same disadvantage as all the other solution - It doesn't protect the coder
from himself (a mistake will not be automatically discovered). The only solution that kinda
does that is the "while" one and it has its own disadvantages (as we discussed).
I disagree.
I'm not seeing a single advantage to the goto. The goto statement has been regarded as evil by the majority of the programming community for decades now and with good reason. You end up with code that is very hard to follow and maintain as you lose all semblance of structured logic when you use it.
The while statement is in the language expressly for the purpose discussed here. It repeats a series of actions until a condition arises when it should stop. That's what it's for and that's what should be used.
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
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by GCDEF
The while statement is in the language expressly for the purpose discussed here. It repeats a series of actions until a condition arises when it should stop. That's what it's for and that's what should be used.
In this case the body of the loop is not something that should be repeated. It merely provides a scope that may be broken out of.
A small detail of that statement, in fact, is the benefit of the loop solution. It uses scope, and in that way fits well into the structured programming paradigm. Using goto in the innocuous way discussed could still be seen as violating the usual structure of a program, which from a holistic standpoint is a severe deterrent from its use. Of course, you need to sift real, practical concerns from all that religious stuff.
Re: Best and Neatest way to check status in C
I assume return values as simple 'bool' - any function will return true if succeeded.
Code:
bool bSuccess;
bSuccess = g1();
bSuccess = bSuccess && g2();
bSuccess = bSuccess && g3();
bSuccess = bSuccess && g4();
bSuccess = bSuccess && g5();
if ( !bSuccess)
// Handle error once and act appropriately.
Here, the value of 'g1' is stored into bSuccess, which would be true/false. In next line, g2 would be called ONLY if g1 was succeeded; so on.
And if return value is always true and false only, we can:And as per OP's code, Status may contain some 'bool' or '&' overload operator.
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by Duoas
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;
}
Clarity is a major component of the argument against goto, so I really don't think an interleaved switch statement provides the best counterargument. Good points for the most part, though.
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by Hermit
... so I really don't think an interleaved switch statement provides the best counterargument.
Heh, yeah, I'd agree with that.
But the interlevity of the switch and if are incidentally fun. It is the nesting of the switch in the while that drives the point.
Though, I can't believe that that particular example is unclear.
Re: Best and Neatest way to check status in C
Sorry this might me lame.. why does one statement better than the other like "goto & while"?? and why is "goto" considered evil; if thats the case why did they ever include it in the Language in the first place??. Sorry i'm new to programming just started 3days ago.
Thanks
Re: Best and Neatest way to check status in C
Quote:
Originally Posted by ch0co
why is "goto" considered evil;
In a nutshell, it encourages poor code structure, and most of its uses have been replaced by better programming constructs such as loops, functions, and exceptions.
One of the best indicators of good code structure is if you can read a function from top to bottom and it makes sense. Reading code that abuses goto, on the other hand, requires one to look up, down, left, right, and under their couch cushions to figure out the flow of execution.
Quote:
Originally Posted by ch0co
if thats the case why did they ever include it in the Language in the first place??
Goto was included in C++ mostly for backwards compatibility with legacy C code. I guess it was included in C because that language was drafted in the early days of structured programming, when using goto to control program flow was still a firmly embedded habit among programmers. To this day there is a small contingent of programmers who feel that goto is useful enough to warrant being a feature of both C and C++, and one of the reasons for this is presented in this thread.
Quote:
Originally Posted by ch0co
Sorry i'm new to programming just started 3days ago.
No apology necessary :). Best of luck.
Re: Best and Neatest way to check status in C
Please go re-read posts 1, 6, 9, 11, and 12.
All computer programs are sequences of instructions and gotos (or branch instructions).
The purpose of a high-level language is to make it easier to organize and maintain the structure of a computer program, by allowing use to use more abstract constructs.
The more abstract the construct (not vague, which is different) the easier it is to manage.
It is the difference between asking someone to make a peanut butter and jelly sandwich and instructing them how to move each muscle in their body to do the same.
However, sometimes you still want to manipulate a specific muscle.
[edit] man... too slow again...
[edit2] i've also got to learn to spell
Re: Best and Neatest way to check status in C
In addition:
At machine/assembly level 'goto' would just break the flow in totally un-conditional manner. Stack variables may not be destroyed, destructor would not be called. Stack may also be corrupted. With exceptions, goto may cripple the whole program flow. The CPU cannot maintain code-coherency (say, code "caching") - thus program would run slow than expected.
There may be be some uninitialized variables, as goto might have skipped the code where variable is initialized.
Debugging with 'gotos' is real pain - you cannot determine the flow while doing code review. It would be hard to maintain code (since flow is jagged!).
Re: Best and Neatest way to check status in C
thnx.. I think I get it now