开发者

Is boolean return type allowed in C?

开发者 https://www.devze.com 2023-03-27 11:28 出处:网络
When I try to compile a function with return type bool in GCC compiler, the compiler throws me this error.

When I try to compile a function with return type bool in GCC compiler, the compiler throws me this error.

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ b开发者_StackOverflowefore ‘comp’

But when I change the return type to int, it is getting compiled successfully.

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?


bool does not exist as a keyword pre-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>.


try to include:

#include <stdbool.h>


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


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;

After all a bool is a 1 or 0

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号