Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding output of printf containing backslash (\012)

Tags:

c

string

printf

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 
like image 817
Radoslaw Krasimirow Avatar asked Apr 23 '15 09:04

Radoslaw Krasimirow


People also ask

How do I print backslash in printf?

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.

What are escape sequence characters give 2 examples?

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.

How do you do a forward slash in C?

printf("| \/\\ \/\\ |"); printf("| \\\/ \\\/ |");


1 Answers

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.

like image 91
unwind Avatar answered Oct 07 '22 22:10

unwind