Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to work with boolean function in c

Tags:

c

boolean

Anyone please tell me, what is wrong in this code

#include<stdio.h>
bool func(char *,int);
void main()
{
   char *a="Interview";
   if(func(a,9))
   {
      printf("True");
   }
   else
   {
      printf("False");
   }

}
bool func(char *s, int len)
{
   if(len < 2)
      return true;
   else
      return s[0] == s[len-1] && func(&s[1], len-2);
}

I believe this function always returns TRUE. This is an interview question. But, when I try to compile this, it shows 6 errors..

like image 328
Ravi Avatar asked Nov 30 '22 22:11

Ravi


2 Answers

I'm going to guess it doesn't know what bool and true are. bool is not a primitive data type in C you need an extra include:

#include <stdbool.h>

The second part of your question? Does it always return TRUE?

No: When you come into the function you'll skip the first return because your length is 9. So instead you'll return if true only if:

return s[0] == s[len-1] && func(&s[1], len-2)

Is true. You can skip the recursive logic here because it's not modifying your string, just look at the first part:

s[0]     // this has to be 'I'
==       // we need so what we compare against has to be 'I' as well
s[len-1] // This will be 'w'

So... that's not going to return true... who cares about ANDing (&&) the recursive part? I suspect the compiler will even optimize that out because everything here is hardcoded.

like image 132
Mike Avatar answered Dec 04 '22 00:12

Mike


You just have to include the right header.

#include <stdbool.h>

Or, you can use _Bool type, which don't need any inclusion. bool is just an alias from this type. By the way, don't forget to compile in C99.

like image 30
md5 Avatar answered Dec 04 '22 02:12

md5