1

What's wrong here? blah=="abcdef" doesn't return a true value

int main(void)
{
  char blah[] = "abcdef";
  if(blah=="abcdef")    
     printf("%s\n", blah);
}
Milap
  • 6,915
  • 8
  • 26
  • 46
Chris Liem
  • 11
  • 1

5 Answers5

1

For comparing strings you should use something like strcmp() instead.

== and != compares base addresses hence they dont actually compare the value of the string.

Always take care when comparing "objects" vs "value of objects"

graN
  • 34
  • 6
1

When you're comparing two strings with ==, you're actually checking equality of the pointers (base address) of the two strings which is obviously always false.

The correct way to compare the two strings would be to either use the inbuilt strcmp() function from <string.h> or to define a string equality checker function by yourself as follows :

int isEqual(char *a,char *b)
    {
    int i=0;
    while(1)
        {
        if(a[i]==b[i])
            {
             if(a[i]=='\0')
                 return 1;
             i++;
             continue;
            }
        else
            return 0;
        }
    }
learner
  • 143
  • 6
0

You are comparing a string literal to a character array. Try below.

Use strcmp() to compare the contents of strings.

OR

char buffer[5];
char word[5] = "WORD";
test(buffer, word, 5);

short test(char buffer[], int length) {
    int i;
    char word[5] = "WORD";
    for(i = 0; i < length; i++) {
        if(buffer[i] != word[i]) {
            return 0;
        }
    }
    return 1;
}
Mohammad Tauqir
  • 1,817
  • 1
  • 18
  • 53
0

I would like to suggest using strcmp()

strcmp(blah, "abcdef");

That will let you compare two strings.

Peter
  • 8,776
  • 6
  • 62
  • 95
Mbigué
  • 21
  • 3
0

You should use strcmp() function to compare string.

blah=="abcdef" return always false because you compare 2 memory address.

int main(void)
{
  char blah[] = "abcdef";
  if(strcmp(blah,"abcdef") == 0 ) //return 0 if equal, !=0 if not equal    
     printf("%s\n", blah);
}
developer
  • 4,744
  • 7
  • 40
  • 55