user2684198
user2684198

Reputation: 852

How does an invalid escape sequence behave in C?

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
int main(void)
{
    printf("\%\n");
    int x = 10;
    printf("\%d\n", x);
        return 0;
}

Output:

10

(The first line is not printing) So what is being done by the escape sequence? If it does not read a % after \, it should not have printed 10 in the second printf statement.

Upvotes: 1

Views: 594

Answers (2)

glglgl
glglgl

Reputation: 91159

There are two levels of processing here:

  1. The parsing of string literals. This is where the \ becomes effective. \n is replaced by the newline character, and other escaping happens as well.

  2. The printf() mechanism. This one only deals with the % as special character, and parses whatever comes after it in order to format one of its arguments.

With \% you intermix these two, whatever happens on the \ (if the % is suppressed or not), (2) won't notice the \ as it is "eaten up" by (1).

Upvotes: 3

haccks
haccks

Reputation: 106132

\% is not a valid escape sequence. Your compiler should raise a warning like

[Warning] unknown escape sequence: '\%' [enabled by default]  

You need %% to print % otherwise it may or may not be printed.

Upvotes: 3

Related Questions