如果发生错误则返回错误值,否则,继续执行功能

时间:2017-07-11 14:16:22

标签: c++ if-statement return-value

有没有更好的(更可读和/或更少重复的代码)方式在C ++中编写它?

int func()
{
  int error = foo(); // can return true/false
  if (error != 0) // if an error is returned from foo(), pass it up to the caller of func()
    return error;

  // otherwise, proceed
  error = bar(); // can return true/false
  if (error != 0)
    return error;

  return error; // all calls succeeded, return 0.
}

5 个答案:

答案 0 :(得分:3)

如果您只想要返回true(非零)或false(零)的指示,而不是被调用函数返回的实际值

 int func()
 {
      return foo() || bar();
 }

如果1foo()返回非零且短路,则会返回bar(),因此如果bar()返回非foo(),则不会调用bool -零。在这种情况下,请考虑返回int而不是foo()

如果bar() int func() { int error = foo(); if (!error) error = bar(); return error; } 可以返回一系列非零值(例如表示不同的错误条件),则需要保留这些值

import ipywidgets as widgets
accordion = widgets.Accordion()
numbers = widgets.Dropdown(options=['1', '2'], value='1')
accordion.children = [numbers]

accordion.set_title(0, 'current value: ' + numbers.value)
def set_title(change):
    display(accordion.get_title(0)) # DEBUG: this shows prover value, however the view doesn't refresh the title 
    accordion.set_title(0, 'current value: ' + change.new)

numbers.observe(set_title, names='value')

display(accordion)

# after displaying, this also doesn't work
accordion.set_title(0, 'current value: whatever') 

答案 1 :(得分:2)

你的版本看起来不错。我唯一要避免的是重复使用相同的变量,而是每个错误使用一个单独的变量并将其严格限制:

int func()
{
  if (int const error = foo())
    return error;

  if (int const error = bar())
    return error;

  return 0;
}

答案 2 :(得分:1)

是:

void func()
{
   foo();
   bar();
}

如果出现意外情况,任何一个函数都会向调用者抛出异常。

错误代码是C-ism。

答案 3 :(得分:0)

如果您经常使用这种结构,我建议您定义monad以隐藏重复行为。一个简单的实现就是这样。

实施

template<typename Return, Return True>
class Monad
{
    Return _result;

public:
    Monad() : _result(True) {}

public:
    template<typename Function, typename... Args>
    Monad&
    call(Function f, Args ...args)
    {
        if (_result == True) {
            _result = f(args...);
        }
        return *this;
    }

    Return result() { return _result; }
};

用法

bool f()      { std::cout << __PRETTY_FUNCTION__ << "\n"; return true; }
bool g(int n) { std::cout << __PRETTY_FUNCTION__ << "\n"; return n == 42; }
bool h()      { std::cout << __PRETTY_FUNCTION__ << "\n"; return true; }

int main()
{
    Monad<bool, true> m;
    const bool result = m.call(f)
                         .call(g, 56)
                         .call(h)
                         .result();
    std::cout << std::boolalpha << result << "\n";
}

在这种情况下,只调用f()g(56)h()不是); result()会返回false

demo

答案 4 :(得分:-1)

您想要outcome<T>

https://ned14.github.io/outcome/

但是为了节省一些按键,你将会引入更大的编译时间。

相关问题