我有这个功能
int f(int x) {
if (x == 0)
return 0;
return 1;
}
是否可以在不使用 if
语句的情况下编写等效函数?
最佳答案
该函数将 x
转换为 bool 值。
您可以使用三元运算符代替 if
语句:
int f(int x) { return x ? 1 : 0; }
有更简单的方法可以做到这一点:
int f(int x) { return x != 0; }
int f(int x) { return !!x; }
您甚至可以使用 C99 bool
类型,但它有点容易出错:
#include <stdbool.h>
int f(int x) { return (bool)x; }
这里有一些有趣的选择:
int f(int x) { return x>0|0>x; }
int f(int x) { return x<0|0<x; }
关于c - 寻找不使用 if 语句的等效函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044342/