C - Library functions - Using strcmp()

In this tutorial we will see how to use the strcmp() function.
It returns:

  • -1 if the first argument is less than the second
  • 0 if the first argument is equal to the second
  • 1 if the first argument is greater than the second

We need the string.h include to use this function.

Let's see this example of the strcmp() function:

// compare.c

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

int     main(int ac, char *av[])
{
  char  *word;
  int   cmp;

  word = "badprog";
  cmp = strcmp(av[1], word);
  if (!cmp)
    printf("Match, indeed, strcmp = %d\n", cmp);
  else
    printf("Do not match, indeed, strcmp = %d\n", cmp);
  return (0);
}

Compiling and executing:

gcc compare.c && ./a.out badprog

Result:

Match, indeed, strcmp = 0

Interesting isn't it?

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.