C语言 如何在c中使用布尔函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13274230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:20:45  来源:igfitidea点击:

how to work with boolean function in c

cboolean

提问by Ravi

Anyone please tell me, what is wrong in this code

任何人请告诉我,这段代码有什么问题

#include<stdio.h>
bool func(char *,int);
void main()
{
   char *a="Interview";
   if(func(a,9))
   {
      printf("True");
   }
   else
   {
      printf("False");
   }

}
bool func(char *s, int len)
{
   if(len < 2)
      return true;
   else
      return s[0] == s[len-1] && func(&s[1], len-2);
}

I believe this function always returns TRUE. This is an interview question. But, when I try to compile this, it shows 6 errors..

我相信这个函数总是返回TRUE. 这是一道面试题。但是,当我尝试编译它时,它显示了6 个错误..

回答by Mike

I'm going to guess it doesn't know what booland trueare. boolis not a primitive data type in C you need an extra include:

我要去猜它不知道什么是booltrue是。bool不是 C 中的原始数据类型,您需要额外的包括:

#include <stdbool.h>

The second part of your question? Does it always return TRUE?

你问题的第二部分? Does it always return TRUE?

No: When you come into the function you'll skip the first return because your length is 9. So instead you'll return if trueonly if:

否:当您进入该函数时,您将跳过第一个返回值,因为您的长度为 9。因此,true只有在以下情况下您才会返回:

return s[0] == s[len-1] && func(&s[1], len-2)

Is true. You can skip the recursive logic here because it's not modifying your string, just look at the first part:

是真的。您可以在这里跳过递归逻辑,因为它不会修改您的字符串,只需查看第一部分:

s[0]     // this has to be 'I'
==       // we need so what we compare against has to be 'I' as well
s[len-1] // This will be 'w'

So... that's not going to return true... who cares about ANDing (&&) the recursive part? I suspect the compiler will even optimize that out because everything here is hardcoded.

所以......这不会返回true......谁在乎ANDing(&&)递归部分?我怀疑编译器甚至会优化它,因为这里的所有内容都是硬编码的。

回答by md5

You just have to include the right header.

您只需要包含正确的标题。

#include <stdbool.h>

Or, you can use _Booltype, which don't need any inclusion. boolis just an alias from this type. By the way, don't forget to compile in C99.

或者,您可以使用_Bool不需要任何包含的类型。bool只是这种类型的别名。顺便说一句,不要忘记在 C99 中编译。