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 six 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 hard coded.