C语言 C 中是否允许布尔返回类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7039618/
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
Is boolean return type allowed in C?
提问by Vivek
When I try to compile a function with return type boolin GCC compiler, the compiler throws me this error.
当我尝试bool在 GCC 编译器中编译具有返回类型的函数时,编译器向我抛出此错误。
error: expected ‘=', ‘,', ‘;', ‘asm' or ‘__attribute__' before ‘comp'
But when I change the return type to int, it is getting compiled successfully.
但是当我将返回类型更改为 时int,它已成功编译。
The function is as below.
功能如下。
bool comp(struct node *n1,struct node *n2)
{
if(n1 == NULL || n2 == NULL)
return false;
while(n1 != NULL && n2 != NULL)
{
if(n1->data == n2->data)
{ n1=n1->link; n2=n2->link; }
else
return false;
}
return true;
}
Here I am comparing two linked lists. Is bool return type supported in C or not?
这里我比较两个链表。C 是否支持 bool 返回类型?
回答by Oliver Charlesworth
booldoes not exist as a keyword pre-C99.
bool不作为关键字存在于 C99 之前。
In C99, it should work, but as @pmg points out below, it's still not a keyword. It's a macro declared in <stdbool.h>.
在 C99 中,它应该可以工作,但正如@pmg 在下面指出的那样,它仍然不是关键字。它是在<stdbool.h>.
回答by user478681
try to include:
尝试包括:
#include <stdbool.h>
回答by Hims Gupta
#include<stdio.h>
#include<stdbool.h>
void main(){
bool x = true;
if(x)
printf("Boolean works in 'C'. \n");
else
printf("Boolean doesn't work in 'C'. \n");
}
回答by Dorathoto
a way to do a manual bool
一种手动布尔值的方法
#define true 1
#define false 0
typedef int bool;
bool comp(struct node *n1,struct node *n2)
{
if(n1 == NULL || n2 == NULL)
return(false);
while(n1 != NULL && n2 != NULL)
{
if(n1->data == n2->data)
{ n1=n1->link; n2=n2->link; }
else
return(false);
}
return true;
ie it is returning 1 or 0, but amiably you get as true and false;
即它返回 1 或 0,但友好地你得到真假;
After all a bool is a 1 or 0
毕竟布尔值是 1 或 0

