Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is boolean return type allowed in C?

Tags:

c

boolean

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__’ before ‘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?

like image 342
Vivek Avatar asked Aug 12 '11 11:08

Vivek


People also ask

Is boolean data type available in C?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.

Can boolean be a return type?

The declared return type for the isEmpty method is boolean , and the implementation of the method returns the boolean value true or false , depending on the outcome of a test.

What is the return type of boolean data type?

The return type is bool, which means that every return statement has to provide a bool expression.


3 Answers

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>.

like image 142
Oliver Charlesworth Avatar answered Sep 17 '22 18:09

Oliver Charlesworth


try to include:

#include <stdbool.h>
like image 38
user478681 Avatar answered Sep 17 '22 18:09

user478681


#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");
}
like image 37
Hims Gupta Avatar answered Sep 19 '22 18:09

Hims Gupta