C:你如何模拟“异常”? [英] C : How do you simulate an 'exception'?

查看:112
本文介绍了C:你如何模拟“异常”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C#背景,但我现在正在学习C。在C#中,当一个人想要发出错误信号时,你会抛出异常。但是你在C做什么?



举个例子,你有一个堆栈, push pop 函数。在 pop 期间,什么是最好的方式来表示堆栈是空的?从该函数返回什么?

  double pop(void)
{
if(sp> ; 0)
return val [ - sp];
else {
printf(error:stack empty\\\
);
返回0.0;
}
}

K& R 的例子(第77页)( 上面的代码)返回一个 0.0 。但是,如果用户在堆栈上稍早推送一个 0.0 ,那么您如何知道堆栈是空还是返回正确的值?

解决方案

C中的异常行为通过了setjmp / longjmp的。但是,您真正想要的是错误代码。如果所有值都可以返回,那么您可能需要以一个out-parameter作为指针,并使用它来返回值,如下所示:

  int pop(double * outval)
{
if(outval == 0)return -1;
if(sp> 0)
* outval = val [ - sp];
else {
printf(error:stack empty\\\
);
return -1;
}
return 0;
}

显然不是很理想,但这是C的限制。 >

此外,如果您走这条路,您可能需要为您的错误代码定义符号常量(或使用一些标准的),以便用户可以区分堆栈空和你给我一个空指针, dumbass。


I come from a C# background, but I'm learning C at the moment. In C#, when one wants to signal that an error has occurred, you throw an exception. But what do you do in C?

Say for example you have a stack with push and pop functions. What is the best way to signal that the stack is empty during a pop ? What do you return from that function?

double pop(void)
{
    if(sp > 0)
        return val[--sp];
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

K&R's example from page 77 (code above) returns a 0.0. But what if the user pushed a 0.0 earlier on the stack, how do you know whether the stack is empty or whether a correct value was returned?

解决方案

Exception-like behavior in C is accomplished via setjmp/longjmp. However, what you really want here is an error code. If all values are potentially returnable, then you may want to take in an out-parameter as a pointer, and use that to return the value, like so:

int pop(double* outval)
{
        if(outval == 0) return -1;
        if(sp > 0)
                *outval = val[--sp];
        else {
                printf("error: stack empty\n");
                return -1;
        }
        return 0;
}

Not ideal, obviously, but such are the limitations of C.

Also, if you go this road, you may want to define symbolic constants for your error codes (or use some of the standard ones), so that a user can distinguish between "stack empty" and "you gave me a null pointer, dumbass".

这篇关于C:你如何模拟“异常”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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