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..
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With