How to work with boolean function in c

Someone will tell me what is wrong with 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 ..

+4
source share
2 answers

I am going to assume that he does not know what bool and true . bool not a primitive data type in C, to which you need to add:

 #include <stdbool.h> 

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

No: When you enter the function, you will skip the first return because your length is 9. Therefore, instead, you will return if true , only if:

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

It's true. You can skip the recursive logic here because it does not change your line, 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 ... what is not going to return the truth ... who cares about the ANDing ( && ) recursive part? I suspect that the compiler even optimizes this, because everything here is hard-coded.

+11
source

You just need to include the right header.

 #include <stdbool.h> 

Or you can use the _Bool type, which does not require any inclusion. bool is just an alias of this type. By the way, do not forget to compile on C99.

+3
source

Source: https://habr.com/ru/post/1444621/


All Articles