-1

So I studied that strcmp returns the difference between the asci value of the two characters being compared. But in my case it is giving a value of -1,0 or 1 only.

#include<stdio.h>
#include<strings.h>
int main()
{
    char n1[]="Jerry";
    char n2[]="Ferry";
    printf("%d",strcmp(n2,n1));
    return 0;
}

Ideally it should give -4,but dev cpp is giving an output of -1. Why is that?

  • 4
    That's fine — all that's required is a positive, negative or zero value; the magnitude is unspecified. Your expectations are wrong. See C11 standard on [`strcmp()`](http://port70.net/~nsz/c/c11/n1570.html#7.24.4.2). – Jonathan Leffler Sep 15 '20 at 07:00
  • 2
    strcmp doesn't do that, you were misled. – n. m. could be an AI Sep 15 '20 at 07:01
  • 2
    You claim: _"strcmp returns the difference between the asci value of the two characters being compared."_. Where did you get this claim from? – Jabberwocky Sep 15 '20 at 07:02
  • 1
    Does this answer your question? [Is this the only return value for strcmp() in C?](https://stackoverflow.com/questions/25015155/is-this-the-only-return-value-for-strcmp-in-c) – user10191234 Sep 15 '20 at 08:14

1 Answers1

0

strcmp gives the relative difference between 2 strings.

negative if the left item is less than right

0 if the left is the same as the right

positive if the left item is greater than the right

It doesn't give a range on the difference.

(HINT: what value for strcmp( "Hello", "Hfllo") ? )

mksteve
  • 12,614
  • 3
  • 28
  • 50
  • Your summarise the spec helpfully though your phrasing "the relative difference" is likely to worsen OPs misunderstanding. Referring/linking to the spec it is probably appropriate. Also you might find ways of formatting your post more readable and suggestive here: https://stackoverflow.com/editing-help – Yunnosch Sep 15 '20 at 07:38
  • 1
    The hint might be less enlightening than you think, because coming up with a formula to determine the answer to the rhetoric question is not so hard and then the reaction is "So what?". – Yunnosch Sep 15 '20 at 07:41