printf("\%")

Oct 16, 2013 at 2:15am
Hello guys, new here, I'm just wonderin' why does it prints nothing? any idea behind it?

I'm not trying to print "%", cause I know how to, what I am curios about is what is happening underneath it?

EDIT:

To summarize, since "printf never sees the \ character" and at compile time printf("\%") backslash will just be ignored since escaping modulus with backslash is not possible, and maybe that's why they use another character to escape it. Thanks Disch.
Last edited on Oct 16, 2013 at 3:08am
Oct 16, 2013 at 2:18am
\ is an escape character, meaning the next character(s) in the string is a special code. It is used to represent characters which are not easy to type.

Examples:

\n is a newline
\r is a carriage return
\t is a tab
\1 is the literal value of 1
\" is a quotation mark (so you can have a quotation mark in the middle of a string literal without ending the string
etc
etc


% is not a valid character to escape. So \% is an invalid escape sequence. Which is why it prints nothing for you. Your compiler should at least be giving you a warning of this.
Last edited on Oct 16, 2013 at 2:19am
Oct 16, 2013 at 2:24am
well compiler does not, thanks for the fast response, but in std::cout it escape the character modulus, so i guess printf just ignore the backslash before the "%", because i tried printf("\%d", 0), it just ignores the backslash and giving me an output of 0.
Last edited on Oct 16, 2013 at 3:08am
Oct 16, 2013 at 2:27am
also anyone knows why printf use another "%" to escape the character "%"? and not "\"?
Last edited on Oct 16, 2013 at 3:08am
Oct 16, 2013 at 2:28am
That makes sense.... it's a bad escape sequence so it just throws out the escape character (\) and leaves the rest of the string (%d) in tact.
Oct 16, 2013 at 2:30am
also anyone knows why printf use another "%" to escape the character "%"? and not "\"?


Because printf never sees the \ character. That's escaped by the compiler at compile time before the string gets passed to printf at runtime.

EDIT:

and it would conflict with printf format rules anyway:
1
2
printf("\02d", 5);  // does this print "05" as per normal printf operation?
    // or does it print "?5" where '?' is the ASCII code with value=2 as the escape sequence would? 
Last edited on Oct 16, 2013 at 2:32am
Oct 16, 2013 at 2:58am
I don't understand what your "EDIT" portion is for. Now I know it happens at compile time. So to summarize, since "printf never sees the \ character" and at compile time printf("\%") backslash will just be ignored since escaping modulus with backslash is not possible, and maybe that's why they use another character to escape it.
Last edited on Oct 16, 2013 at 3:08am
Topic archived. No new replies allowed.