Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is percentage character not escaped with backslash in C?

Tags:

The printf() documentation says that if someone wants to print % in C, he can use:

printf("%%") 

Why is it not:

printf("\%") 

as with other special characters?

like image 762
acgtyrant Avatar asked Jul 23 '13 13:07

acgtyrant


People also ask

How do you escape the backslash character?

Querying Escape Characters To escape the backslash escape character, use \\ .

Does forward slash need to be escaped in C?

You don't need to escape forward slash.

What is the use of backslash T in C?

\t (Horizontal tab) – We use it to shift the cursor to a couple of spaces to the right in the same line. \a (Audible bell) – A beep is generated indicating the execution of the program to alert the user.


2 Answers

The backslash is processed by the compiler when interpreting the source text of the program. So the common result is that the source text "\%" produces a string containing ”%”.

The format string is interpreted by the printf routine, so it processes the characters passed to it. By this time, the backslash is no longer present, so printf never sees it.

Technically, \% is not legal in a string literal. The character \ starts an escape sequence, and the only legal escape sequences are listed in C 2011 6.4.4.4 1. They are \ followed by ', ", ?, \, a, b, f, n, r, t, v, one to three octal digits, x and hexadecimal digits, u and four hexadecimal digits, or U and eight hexadecimal digits.

If printf had been designed so that a backslash would escape a percent, then you would have to pass it a backslash by escaping the backslash in the source text, so you would have to write:

printf("\\%"); 
like image 194
Eric Postpischil Avatar answered Oct 14 '22 18:10

Eric Postpischil


Because the % is handled by printf. It is not a special character in C, but printf itself treats it differently.

like image 20
Kninnug Avatar answered Oct 14 '22 18:10

Kninnug