当我尝试在GCC编译器中编译返回类型为bool
的函数时,编译器会抛出此错误。
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘comp’
但是当我将返回类型更改为int
时,它已成功编译。
功能如下。
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;
}
我在这里比较两个链表。 C中是否支持bool返回类型?
答案 0 :(得分:21)
bool
不存在于C99之前的关键字。
在C99中,它应该有效,但正如@pmg在下面指出的那样,它仍然不是关键字。它是<stdbool.h>
中声明的宏。
答案 1 :(得分:8)
尝试包括:
#include <stdbool.h>
答案 2 :(得分:2)
#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");
}
答案 3 :(得分:0)
手动布尔的方法
#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;
即它返回1或0,但很可能您会得到true和false;
毕竟布尔是1或0