Search code examples
cstringcomparestrcmp

Comparing "" and "" in C


So I have the following test code:

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

int main(int argc, char* argv[]){
  int retVal = strcmp("", "");
  printf("%d\n", retVal);
  return 0;
}

And for me, it always seems print out 0, i.e. "" and "" are always equal one another. But I'm curious. Is this something guaranteed by strcmp, or does it have the potential to vary from implementation to implementation? Maybe I'm just being paranoid, but I've worked on enough strange systems to know the perils of differing implementations.

UPDATE: I've decided to clarify to justify my paranoia. What I'm really doing in my program is more akin to this:

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

int doOperation(const char* toCompare){
  //do stuff in here
  int compResult = strcmp(toCompare, "");
  //do more stuff depending on compResult
}

int main(int argc, char* argv[]){
  const char* myString = "";
  doOperation(myString);
  return 0;
}

I want to make sure things in doOperation will proceed correctly. Note that this is just an example. In my doOperation function I'm not going to actually know that the value of toCompare.


Solution

  • A string is equal to another string if all the characters before the NULL terminator of both strings are exactly the same. Since "" has no characters, it fits that definition when compared with "".