C:你如何来模拟一个“例外”? [英] C : How do you simulate an 'exception'?
问题描述
我来自一个C#背景,但我目前学习C。在C#中,当一个人想要的信号已发生错误,则抛出异常。但是你怎么用C呢?
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&放大器;从第77页(S R 例子的 code时上部的)返回一个 0.0
。但是,如果用户按下一个 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?
推荐答案
在C异常类似的行为是通过的setjmp /完成longjmp的。但是,你真的想在这里什么是错误code。如果所有的值都是潜在的可回收,那么你可能想在out参数为指针,并用它来返回值,像这样:
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;
}
不理想,很明显,但这样是C的局限性。
Not ideal, obviously, but such are the limitations of C.
另外,如果你走这条路,你可能要定义符号常量为你的错误codeS(或者使用一些的the标准的人的),使用户可以区分堆空和你给了我一个空指针,笨蛋。
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屋!