Odd results for strcmp / strncmp for empty string

strcmp and strncmp returns are
<0 the first character that does not match has a lower value in str1 than in str2
0 the contents of both strings are equal

0 the first character that does not match has a greater value in str1 than in str2

So you would expect when comparing an empty string with a non-empty string that the result would always be != 0
however
strncmp(nonEmpty,empty,strlen(empty)) returns 0
while
strncmp(nonEmpty,empty,strlen(nonEmpty)) returns non-zero
which seems odd

char empty[] = "";
char nonEmpty[] = "a";
void setup() {
  // Open serial communications and wait a few seconds
  Serial.begin(9600);
  for (int i = 10; i > 0; i--) {
    Serial.print(' '); Serial.print(i);
    delay(500);
  }
  Serial.println();
  Serial.print("strcmp(nonEmpty,empty):");Serial.println(strcmp(nonEmpty,empty));
  Serial.print("strncmp(nonEmpty,empty,strlen(empty)):");Serial.println(strncmp(nonEmpty,empty,strlen(empty)));
  Serial.print("strncmp(nonEmpty,empty,strlen(nonEmpty)):");Serial.println(strncmp(nonEmpty,empty,strlen(nonEmpty)));
} 
void loop() {
}

drmpf:
So you would expect when comparing an empty string with a non-empty string that the result would always be != 0
however
strncmp(nonEmpty,empty,strlen(empty)) returns 0

Why would I expect a function that only has permission to test count characters test more than that?

strncmp(nonEmpty,empty,strlen(empty))
[code]

strlen(empty) is 0, so you are comparing zero characters, a pretty pointless thing to do.  But what, to you, is a logical return value when you compare NO characters?

strncmp(nonEmpty,empty,strlen(nonEmpty))
[/code]

The first characters of each string will be compared, and they will surely NOT be equal. So, of course, it returns non-zero.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.