c - 寻找不使用 if 语句的等效函数

标签 c function if-statement

我有这个功能

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/

相关文章:

c++ - 我可以使用没有指针的 fread 读取动态长度变量吗?

python - 更改导入的类变量

python - 如何设置 if 语句以使用条件数组作为 python 中的输入

c - 如何使用重复功能创建向上三角形

java - 对数组使用 if 语句

java - 为什么两个相等的字符串不匹配?

c++ - 什么时候 sizeof(myPOD) 太大而无法在 x64 上按值传递?

c - fedora 22 链接共享对象时出现多个 undefined reference 错误

c - 堆栈内存中的 free()

algorithm - 确定一个符号是否是第 i 个组合 nCr 的一部分