0

如果遇到错误,我有一些函数会返回 1。每个函数调用一个较低级别的函数,这样如果较低级别的函数返回 1,则原始函数也返回 1。因此,错误以这种方式向上传递。

这是其中一个功能的高度删节版本:

if (low_level_function()) {
    [do stuff]
    return 1;
}
[do other stuff]
return 0;

我应该改为声明一个错误变量,将 low_level_function() 的结果分配给它,然后在 if() 语句中使用错误变量吗?换句话说:

int error = low_level_function();
if (error) {
    [do stuff]
    return 1;
}
[do other stuff]
return 0;

或者还有另一种更好的方法吗?我以前从未编写过代码来解释错误,所以我在这里的经验相当有限。

编辑:我重新格式化了函数以更好地传达我的代码的性质。

4

4 回答 4

2

One reason to prefer the second form is when you don't have anything to do in the error case and you want to avoid the stair-step effect of nested if statements.

int error_flag = low_level_function();
if (!error_flag)
    error_flag = second_function();
if (!error_flag)
    error_flag = third_function();
return error_flag;

Of course for that specific example you can really simplify by using the short-circuiting property of ||:

return low_level_function() || second_function() || third_function();
于 2012-05-04T17:18:42.493 回答
1

你也可以用这个,

return low_level_function();

If low_level_function() returns nonzero on error and zero on success. Or

return low_level_function()>0? 1 : 0;
于 2012-05-04T15:50:08.207 回答
1

I dont see the difference between the two approaches above.

I would recomment using exception, much more cleaner approach. why the reinvent the wheel? You can either use standard exception or implement custome exception like

于 2012-05-04T15:52:07.423 回答
0

Although it it's s side comment I´ll be first stateing that I prefer one exit for any method.

One major pro tof his construction is the possiblity to only have the need for a error-logging statement at one place.

Also it's very easy to add tracing logs for debugging porpose.

So following this idea I'd propose the following

#define OK (0)

int mid_level_func(....)
{
  log_entry(...);

  int rc = OK

  {
    ...

    if ((rc = low_level_func1(...)))
      goto lblExit;

    ...

    if ((rc = low_level_func2(...)))
      goto lblExit;

    ...

    lblExit:
    ;
  }

  if (OK != rc)
    log_error(rc, ...);

  log_exit(...);

  return rc;
}

For the ones that insist on goto being 'evil' the following variation on the scheme above might help:

#define OK (0)

int mid_level_func(....)
{
  log_entry(...);

  int rc = OK

  do 
  {
    ...

    if ((rc = low_level_func1(...)))
      break;

    ...

    if ((rc = low_level_func2(...)))
      break;

    ...

  } while (0);

  if (OK != rc)
    log_error(rc, ...);

  log_exit(...);

  return rc;
}
于 2012-05-04T18:43:02.157 回答