-3

If I write putchar('\\t'); while trying to print "\t" instead of an actual tab, I get the multi character constant warning. On the other hand, if I write putchar('\\'); I get no warning. Upon looking in the ASCII table, there is no character '\\', only '\'. So why is there no warning? Why is '\\' one character but '\\t' is more than one? Can a backslash only be used to escape one following character?

Sahand
  • 7,980
  • 23
  • 69
  • 137

2 Answers2

2

You cannot print \ and t with one putchar invocation, since putchar puts one and exactly only one character into the standard output. Use 2:

putchar('\\');
putchar('t');

Another option would be to use the string "\\t" with fputs:

fputs("\\t", stdout);

There is no warning for '\\' because that is one way how you enter the character literal for the character \. On ASCII this is synonymous with '\134' and '\x5c'.

From C11 6.4.4.4 paragraphs 2 and 4:

2

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'. [...] With a few exceptions detailed later, the elements of the sequence are any members of the source character set; they are mapped in an implementation-defined manner to members of the execution character set.

[...]

4

The double-quote " and question-mark ? are representable either by themselves or by the escape sequences \" and \?, respectively, but the single-quote ' and the backslash \ shall be represented, respectively, by the escape sequences \' and \\.


The reason why you get a warning for this is that the behaviour is wholly implementation-defined. In C11 J.3.4 the following is listed as implementation-defined behaviour:

The value of an integer character constant containing more than one character or containing a character or escape sequence that does not map to a single-byte execution character (6.4.4.4).

Since '\\' contains an escape sequence that maps to a single-byte execution character \, there is no implementation-defined pitfalls, and nothing to warn about; but \\t contains 2 characters: \ and t, and it wouldn't do what you want portably.

Community
  • 1
  • 1
1

\\ is one character, t is one character, so that is clearly two characters.

\\ is an escape sequence, just like \t; it means \.

If you want to print the two characters \ and t, you clearly need either two calls to putch() or a function that takes a string argument "\\t".

https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences

Clifford
  • 88,407
  • 13
  • 85
  • 165