c - 如何在三元条件中放入返回语句?

标签 c

<分区>

我知道三元条件需要表达式才能工作,但我想知道是否有像这样的聪明的解决方法:

#include <stdbool.h>

bool in_asc_order(const int *arr, size_t arr_size)
{
    int count = 0;
    bool result = false;

    while(count < arr_size - 1)
    {
        (arr[count] <= arr[count + 1])? result = true : (return false);
        count++;
    }

    return result;
}

而不是像这样写:

#include <stdbool.h>

bool in_asc_order(const int *arr, size_t arr_size)
{
    int count = 0;
    bool result = false;

    while(count < arr_size - 1)
    {
        if(arr[count] <= arr[count + 1])
        {
            result = true;
        }
        else
        {
            return false;
        }
        count++;
    }

    return result;
}

我热衷于使用这个条件。任何帮助都会很棒。

最佳答案

我不会写这些东西。这个怎么样?

bool in_asc_order(const int *arr, size_t arr_size)
{
  if (arr_size == 0)
    return true;
  for (size_t i = 0; i < arr_size - 1; i++)
    if (arr[i] > arr[i + 1])
      return false;
  return true;
}

关于c - 如何在三元条件中放入返回语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213256/

相关文章:

c - 在 CGI 应用程序中维护 session 状态的最佳 C/C++ 库?

c - 使用C在SDL2中移动一个正方形

c - 一种在 C 中自动将字符串文字转换为 `unsigned char*` 的方法?

c++ - 开源 C/C++ 3d 渲染器(支持 3ds max 模型)

c# - 从 C 到 C# 的编码(marshal)结构

c++ - 在 VBA 中声明变量注册表?

c - 如何从 C 中的排序数组更新或同步树

C 编程 - Malloc 结构和未定义数组

c - 服务器只能接受n个客户端

c++ - 使用 alloca 函数时崩溃,但使用 malloc 时正常