是否有从 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;}
3 回答
哆啦的时光机
TA贡献1779条经验 获得超6个赞
为什么不试一试:
if ((e = do_something()) != 0) return e;
// ...rest of the code when no error.
这使得它一行一行,但读起来不太清楚。此处应用了运算符优先级规则,因此前面和之前的括号显然是必需的。e0
PIPIONE
TA贡献1829条经验 获得超9个赞
我喜欢在这种特定情况下使用宏:
#define CHECK_SUCCESS(cmd) \
do \
{ \
int e = cmd; \
if (0 != e) \
return e; \
} while (0);
然后,每当您要检查函数是否成功时:
CHECK_SUCCESS(do_something());
CHECK_SUCCESS(my_func(arg));
慕慕森
TA贡献1856条经验 获得超17个赞
从 c++17 开始,您可以在 if 中使用 init 语句。
if (int e = do_something(); e != 0) {
return e;
}
// ... rest
- 3 回答
- 0 关注
- 140 浏览
添加回答
举报
0/150
提交
取消
