为什么我不是在C使用exit函数? [英] Why should I not use exit function in C?

查看:142
本文介绍了为什么我不是在C使用exit函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经作出了一些学校的项目,我已经使用此功能错误输出:

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.");

信息将显示给用户,并计划将错误code退出。

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);
}

感谢您的时间。

推荐答案

这真的取决于你如何编程,或在这种情况下,你的老师怎么要你编程。结果
在这种情况下,最好的答案,就是去你的老师,要求一个解释,为什么这是错的。

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.

当我在C程序中,我所有的功能总是返回 INT (或的typedef <$ C $的C> INT ),然后我可以从函数返回的错误。然后我的因为它返回主函数返回一个错误。事情是这样的模板:

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
}

使用这个模板时,如果有错误,1人从返回主的功能,并且在成功的情况下,0将被返回。同时,您可以添加一个条件,如果在函数,检查的FUNC 的返回值。这使你在code来处理错误的选项。

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.

这篇关于为什么我不是在C使用exit函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆