I am trying to implement a string compare function where I want to return a bool value but I am getting several errors and I don't know why is that so.
The error that the compiler shows is
"error: unknown type name bool"
&
"error: false, true undeclared"
now as far as I know, bool has only two values i.e. true or false, then why am I still having problem?
bool string_cmp(char word1[],char word2[]){
bool isEqual = false;
int i,k=sizeof(word1);
for(i=0;i<=k;i++){
if(word1[i]!=word2[i]){
isEqual=false;
}
else
isEqual=true;
break;
}
return isEqual;
}
Edited code(why is my output wrong when I am adding more words in word1 array?):
bool string_cmp(char word1[],char word2[]){
bool isEqual = false;
int i,k=sizeof(word1);
for(i=0;i<=k;i++){
if(word1[i]!=word2[i]){
isEqual=false;
break;
}
else
isEqual=true;
}
return isEqual;
}
int main()
{
int count;
bool cmp;
char word1[40]={"Hi world world"},word2[20]={"Hi world"},result[60]; //the only case when I am getting wrong output; otherwise if both words are same or if I remove something from word2, I get the output as expected.
cmp=string_cmp(word1,word2);
printf("%d",cmp);
}
bool
is not a built-in type. Refer this: stackoverflow.com/questions/1921539/using-boolean-values-in-c – user218867k=sizeof(word1)
should bek=strlen(word1);
and also you have logic erors in your loop – M.M