Home > Software engineering >  Compare string with ">", "<", "=" in c
Compare string with ">", "<", "=" in c

Time:10-25

I want to know what is compared when we have s1 > s2 and what is the result (for example when we compare chars their ASCII corresponding codes are compared). I read that with this operation are compared the first chars of s1 and s2, but if I try to compare with s1[0] > s2[0] the result is different, then it cannot be that.

CodePudding user response:

Comparing with == means checking if the pointers point to the same object, so this:

char s1[] = "foo";
char s2[] = "foo";
if(s1 == s2) 
    puts("Same object");
else
    puts("Different object");

would print "Different object".

< and > makes absolutely no sense unless the pointers are pointing to the same object. For instance, you could do like this:

char s[] = "asdfasdf";
char *p1 = &s[3], *p2 = &s[6];
if(p1 < p2) 
    // Code

CodePudding user response:

If you have character arrays like for example

char s1[] = "Hello";
char s2[] = "Hello";

then in an if statement like for example this

if ( s1 == s2 ) { /*,,,*/ }

the character arrays are implicitly converted to pointers to their first elements.

So the above statement is equivalent to

if ( &s1[0] == &s2[0] ) { /*,,,*/ }

As the arrays occupy different extents of memory then the result of such a comparison will be always equal to logical false.

If you want to compare strings stored in the arrays you need to use the standard string function strcmp declared in the header <string.h>.

For example

#include <string.h>
#include <stdio.h>

//...

if ( strcmp( s1, s2 ) == 0 )
{
    puts( "The strings are equal." );
}
else if ( strcmp( s1, s2 ) < 0 )
{
    puts( "The first string is less than the second string." );
}
else
{
    puts( "The first string is greater than the second string." );
}

CodePudding user response:

You could use the following macro that might be considered a slight abuse of preprocessor.

#define STROP(a, OP, b) (strcmp(a, b) OP 0)

Examplary usage:

STROP(s1, >=, s2) // expands to `strcmp(s1,s2) >= 0`

STROP(s1, ==, s2) // expands to `strcmp(s1, s2) == 0`
  • Related