prev up next   top/contents search

comp.lang.c FAQ list · Question 10.12

Q: How can I construct preprocessor #if expressions which compare strings?


A: You can't do it directly; preprocessor #if arithmetic uses only integers. An alternative is to #define several macros with symbolic names and distinct integer values, and implement conditionals on those:

	#define RED	1
	#define BLUE	2
	#define GREEN	3

	#if COLOR == RED
	/* red case */
	#else
	#if COLOR == BLUE
	/* blue case */
	#else
	#if COLOR == GREEN
	/* green case */
	#else
	/* default case */
	#endif
	#endif
	#endif
(Standard C specifies a new #elif directive which makes if/else chains like these a bit cleaner.)

See also question 20.17.

References: K&R2 Sec. 4.11.3 p. 91
ISO Sec. 6.8.1
H&S Sec. 7.11.1 p. 225


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

Hosted by Eskimo North