2011-08-12 50 views
7

當我嘗試在GCC編譯器中編譯返回類型爲bool的函數時,編譯器會引發此錯誤。是C中允許的布爾返回類型嗎?

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

什麼是'foo'? –

+0

對不起。我編輯過。現在檢查。 – Vivek

+1

如果n1和n2都爲NULL,則可能要返回true。 – eyalm

回答

16

bool作爲關鍵字pre-C99不存在。

在C99中,它應該可以工作,但@pmg在下面指出,它仍然不是關鍵字。這是一個在<stdbool.h>中聲明的宏。

+0

所以,你的意思是說它不能在GCC編譯器中工作? – Vivek

+5

+1'bool'是C99關鍵字和預定義類型「_Bool」的typedef(在''中)。 – pmg

+0

@pmg:好點。澄清了我的答案。 –

7

嘗試包括:

#include <stdbool.h> 
+0

是的。這工作。 +1。 :D – Vivek

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"); 
} 
+0

請加入一些內容 – Rajesh