问题
I've been making some school project and I've used this function for error outputs:
void errorMsg(char* msg)
{
fprintf(stderr, msg);
exit(EXIT_FAILURE);
}
So I can do something like this:
if (condition)
errorMsg("Error, Wrong parameters.");
Message will be shown to user and program will exit with error code.
But I've recieved minus points for using exit
function.
So I was just wondering how should I do it? Is there some another way than writing this for several times in main function?
if (condition)
{
fprintf(stderr, "Error, Wrong parameters.");
return(EXIT_FAILURE);
}
Thanks for you time.
回答1:
It really depends on how you program, or in this case, how your teacher wants you to program.
The best answer at this case, is to go to your teacher and ask for an explanation why this is wrong.
When I program in C, all my functions always return int
(or a typedef
of int
) and then I can return errors from functions. Then my main
function returns an error as it returns. Something like this template:
int func(void)
{
int return_value = 0;
if (/* Some condition */) {
return_value = 1
}
/* Some code */
return return_value;
}
int main(void)
{
int return_value = 0;
return_value = func();
return return_value
}
Using this template, if there is an error, 1 would be returned from the main
function, and in case of success, 0 would be returned. As well, you can add an if condition in the main
function, to check the return value of func
. This gives you the option to handle errors in your code.
回答2:
One important reaons:
If you have some code which has opened files, but not yet finished to write in them, and this piece of code delegates some work to a function that will end the program, what happens?
Right, you´ll get a broken file.
Same reasoning is valid for allocated memory, open handles of any kind, etc.etc.
Instead of thinking everytime if the function could end the program, don´t write such functions in the first place. It doesn´t matter if everything is ok or not, but return the "control" after a function to the caller everytime. The only place where exit
could be ok is main, because it will basically do the same thing as return there. And in main, there´s no reason to not write return
in the first place.
回答3:
My opinion is that exit functions are harder to test. I struggled a lot while testing a function that has exit call.
来源:https://stackoverflow.com/questions/27069451/why-should-i-not-use-exit-function-in-c