Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!nstn.ns.ca!news.cs.indiana.edu!att!linac!pacific.mps.ohio-state.edu!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!emory!gatech!udel!rochester!pt.cs.cmu.edu!o.gp.cs.cmu.edu!andrew.cmu.edu!vd09+ From: vd09+@andrew.cmu.edu (Vincent M. Del Vecchio) Newsgroups: comp.sys.mac.programmer Subject: Re: New Think C user Message-ID: Date: 9 Feb 91 07:41:18 GMT References: <21005@sri-unix.SRI.COM> Organization: Carnegie Mellon, Pittsburgh, PA Lines: 42 In-Reply-To: <21005@sri-unix.SRI.COM> mxmora@sri-unix.SRI.COM (Matt Mora) writes: > I have a beginning C programming question. This question came up in my > C class and the instructor didn't now the anwser. Why do you have to use > a double percent sign in a string literal to have it print a percent sign > when all logic would indicate that a backslash percent sign should work? > A subtle difference. The thing you need to know is that \a, \b, \n, \\, etc., get interpreted by the compiler. "foo\n" is represented as 4 characters after compilation. I'm not sure what K&R says about "\%", for example, or other combinations of "\" which aren't specifically covered. I imagine that it would either be compiled to { '\\', '%' } or just { '%' } but I'm not sure which. The important point is that the backslashes are simply a device to represent otherwise unrepresentable characters to the compiler. The % operands, on the other hand, have no significance to the compiler and are perfectly legitimate parts of strings. For example, you can char a[10] = "%"; char *b = "d"; int i = 12; printf(strcat(a,b),i); and you will get "12". On the other hand, you can't do char a[10] = "\"; char *b = "n"; printf(strcat(a,b)); since a "\n" is actually a single character (here the compiler would complain that the string constant "\" is unterminated). The % operands only have special meaning to printf and scanf. When printf sees a "%" in your format string, it looks at the next couple of characters to see what kind of data you are sending it. printf could have been written to accept "\\%" (2 characters) as an instruction to print a single percent, but that would involve making '\\' a special character as well, and within printf, '\\' is not a special character. Also, then you would have to give it "\\\\%" to get it to print \% on your screen. Also, printf follows the more general convention that when you have a sort of escape character (like '\\' at the compiler level, or '%' at the printf level), doubling it removes any special meaning the character has. Hope this answers your question...