Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

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.

Upvotes: 2

Views: 151

Answers (2)

user606087
user606087

Reputation:

No it won't vary with different implementations as C code is compiled to machine specific code and strcmp() will do the same in all platforms. You will get the same result everywhere. I also agree with Seth Carnegie's answer.

Upvotes: 3

Seth Carnegie
Seth Carnegie

Reputation: 75130

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 "".

Upvotes: 8

Related Questions