-2

Possible Duplicate:
Why does strcmp() return 0 when its inputs are equal?
strcmp results in false when strings are equal

I really can´t get why the function check return true!!! I use strcmp to compare the char[] pointer (hello) and the array of chars "bar".

bool check(const char* word);
char pointer[] = "hello";  

int main (void)
{
    bool answer = check(pointer) ;

    if(answer == true)
        printf("true");
    else
        printf("false");

    return 0;
}

bool check(const char* word)
{
    printf(" word = %s ", word);

    if(strcmp( word , "bar"))
        return true;
    else
        return false;
}
Community
  • 1
  • 1
jotape
  • 319
  • 2
  • 6
  • 14
  • 1
    `strcmp` returns non-zero when strings are different. – imreal Jan 30 '13 at 00:27
  • 5
    Read The Fine Manual. Specifically, for [`strcmp`](http://linux.die.net/man/3/strcmp). –  Jan 30 '13 at 00:28
  • is the other way around!!. – jotape Jan 30 '13 at 00:32
  • http://stackoverflow.com/questions/595450/why-does-strcmp-return-0-when-its-inputs-are-equal , http://stackoverflow.com/questions/7656475/strcmp-return-values-in-c –  Jan 30 '13 at 00:38

2 Answers2

4

I really can´t get why the function check return true!!!

Interestingly in raw basic C code there's no "true" or "false" (or "bool") with out including some extra header files (like stdbool.h)... but I digress..

It's not returning true. Read the manual on strcmp(). You can do this by man 3 strcmp on Linux or just google search "man strcmp".

The manual will tell you the return value of the function is:

... an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

Keep in mind that all integer values that are not 0 will be considered "true" for conditional checks. So that is to say in this code:

if(strcmp(word, "bar"))

Any word which is not "bar" will be "true". What you want for a match is if it is equal to zero:

if(strcmp(word, "bar") == 0)

side note, if you're going to declare something in the global scope like you do with

char pointer[] = "hello";  

It's not needed to pass it to the function, you can access it globally, which is the point of a global. Globals are, however, generally frowned upon.

Mike
  • 47,263
  • 29
  • 113
  • 177
3

strcmp returns 0 if the strings are equal.

Your conditional should be negated:

if(!strcmp( word , "bar"))
    return true;

or compared to 0:

if(strcmp( word , "bar") == 0)
    return true;
Adrián
  • 6,135
  • 1
  • 27
  • 49