4

誰でも教えてください、このコードのどこが間違っていますか

#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);
}

この関数は常に を返すと思いますTRUE。これはインタビューの質問です。しかし、これをコンパイルしようとすると、6つのエラーが表示されます..

4

2 に答える 2

16

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.

于 2012-11-07T16:45:47.410 に答える
4

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.

于 2012-11-07T16:46:02.840 に答える