在 C 中是否有返回条件整数(错误代码)的简写?这有点类似于围棋

是否有从 C 中的函数返回条件错误代码的简写?从下面这样:


int e = 0; // Error code.

e = do_something()

if (e)

  return e;


// ...rest of the code when no error.

在 Go 中,您可以执行以下操作:


if err := doSomething(); err != nil {

  return err;

}


慕工程0101907
浏览 141回答 3
3回答

哆啦的时光机

为什么不试一试:if ((e = do_something()) != 0) return e;// ...rest of the code when no error.这使得它一行一行,但读起来不太清楚。此处应用了运算符优先级规则,因此前面和之前的括号显然是必需的。e0

PIPIONE

我喜欢在这种特定情况下使用宏:#define CHECK_SUCCESS(cmd) \    do \    { \        int e = cmd; \        if (0 != e) \            return e; \    } while (0);然后,每当您要检查函数是否成功时:CHECK_SUCCESS(do_something());CHECK_SUCCESS(my_func(arg));

慕慕森

从 c++17 开始,您可以在 if 中使用 init 语句。if (int e = do_something(); e != 0) {    return e;}// ... rest
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go