Can you please help me to understand the output of this simple code:
const char str[10] = "55\01234"; printf("%s", str);
The output is:
55 34
How to Print backslash(\) We will discuss the C program to understand How to Print backslash(\) It is very easy, we just have to use “\\” format specifier withing printf(), for printing backslash(\), on the output screen.
An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character. It is composed of two or more characters starting with backslash \. For example: \n represents new line.
printf("| \/\\ \/\\ |"); printf("| \\\/ \\\/ |");
The character sequence \012
inside the string is interpreted as an octal escape sequence. The value 012
interpreted as octal is 10
in decimal, which is the line feed (\n
) character on most terminals.
From the Wikipedia page:
An octal escape sequence consists of
\
followed by one, two, or three octal digits. The octal escape sequence ends when it either contains three octal digits already, or the next character is not an octal digit.
Since your sequence contains three valid octal digits, that's how it's going to be parsed. It doesn't continue with the 3
from 34
, since that would be a fourth digit and only three digits are supported.
So you could write your string as "55\n34"
, which is more clearly what you're seeing and which would be more portable since it's no longer hard-coding the newline but instead letting the compiler generate something suitable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With