print % in c

Tim Olson tim at proton.amd.com
Wed Feb 27 13:06:29 AEST 1991


In article <31530035 at hpcvia.CV.HP.COM> brianh at hpcvia.CV.HP.COM (brian_helterline) writes:
| haozhou at acsu.buffalo.edu (Hao Zhou) writes:
| >since % and \ are recognized as special characters in printf, how do
| >you print out such kind special chars using printf?
| 
| Any character following a \ will be taken literally so just preceed
| any "special" char with a \ so:
| 
| 	printf( "This is a slash \\ and a precent sign \%\n" )
| 
| would produce: This is a slash \ and a percent sign %

No, it would produce: This is a slash \ and a percent sign
				     [note missing % !!!]  ^

The real answer is that '\' is a special escape character for
character constants and strings in C, and it is processed at
compile/assemble time.  It can be used to represent frequently used
values (e.g. \t = tab, \r = return, \n = newline, \\ = \), as well any
character by following the backslash with an octal constant.

printf(), on the other hand, uses '%' as its escape character, and
interprets it at runtime.  To get printf to print a '%' character, you
need to escape it with another %:

	printf("This is a percent sign: %%\n");


--
	-- Tim Olson
	Advanced Micro Devices
	(tim at amd.com)



More information about the Comp.lang.c mailing list