logisoul
logisoul

Reputation: 15

If both var have same value why it will show not equal

Here is my code can anyone tell me why the compiler prints "both are not equal " message when I put the same value in both variable a and b.

(Note: I don't want to compare strings I just need the technical reason).

#include<stdio.h>
main()
{
    char a[3]="abc",b[3]="abc";
    if(a==b)
        printf("both are equal");
    else
        printf("both are not equal");
}

Upvotes: 1

Views: 455

Answers (4)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158479

a and b are arrays and with the exception of sizeof and & they decay to pointers to the first element of the array and since they occupy different storage locations the pointer will not be equal. If we look at the C99 draft standard section 6.3.2.1 Lvalues, arrays, and function designators paragraph 3 says (emphasis mine):

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

The C FAQ question 6.3 also covers this topic well.

The correct way to compare C style strings is to use strcmp, from the linked document:

int strcmp( const char *lhs, const char *rhs );

and it is described as:

Compares two null-terminated byte strings. The comparison is done lexicographically.

with the following return value:

  • Negative value if lhs is less than rhs.
  • ​0​ if lhs is equal to rhs.
  • Positive value if lhs is greater than rhs.

Upvotes: 1

exexzian
exexzian

Reputation: 7890

Because their addresses are different (check the output here) and if you intended to compare their values, it is better use strcmp(a,b)

Upvotes: 0

ThePelaton
ThePelaton

Reputation: 41

The name of an array is its address, not its content, thus, two different arrays, regardless of content, will 'miscompare'.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753990

C doesn't do string comparisons. It will be comparing the two pointers that point to the start of the arrays, and they'll never be equal.

Use strcmp() to compare strings:

  • strcmp(a, b) == 0 for equality
  • strcmp(a, b) != 0 for inequality
  • strcmp(a, b) < 0 for a sorts before b
  • strcmp(a, b) <= 0 for a sorts before or is equal to b
  • strcmp(a, b) > 0 for a sorts after b
  • strcmp(a, b) >= 0 for a sorts after or is equal to b

Upvotes: 5

Related Questions