prev up next   top/contents search

comp.lang.c FAQ list · Question 8.2

Q: I'm checking a string to see if it matches a particular value. Why isn't this code working?

	char *string;
	...
	if(string == "value") {
		/* string matches "value" */
		...
	}


A: Strings in C are represented as arrays of characters, and C never manipulates (assigns, compares, etc.) arrays as a whole.[footnote] The == operator in the code fragment above compares two pointers--the value of the pointer variable string and a pointer to the string literal "value"--to see if they are equal, that is, if they point to the same place. They probably don't, so the comparison never succeeds.

To compare two strings, you generally use the library function strcmp:

	if(strcmp(string, "value") == 0) {
		/* string matches "value" */
		...
	}


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North