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);
    printf("Do not match, indeed, strcmp = %d\n", cmp);
  return (0);

Compiling and executing:

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


Match, indeed, strcmp = 0

Interesting isn't it?

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.