# Writing a backslash in the \texttt environment

How do you go about writing a backslash inside \texttt? The $\backslash$ trick makes the font inconsistent. The reason I am asking is that I am writing some introductory computer science material and need to talk about different escape characters in printf and other functions. The verbatim environment adds new lines while I would like my finished product to be strictly inline.

How about using \verb instead of \texttt?

The first exercise uses \verb$printf("Hello world!\n");$.


You can use (almost) any character you like instead of $. Better still, if you're typesetting a lot of code, use the listings package that provides a \lstinline macro, equivalent to \verb but with syntax highlighting. • Great! Didn't know that verbatim had an inline shortcut. That is really handy! – Thomas James Sep 4 '13 at 23:22 • There is also \texttt{printf("Hello world!\string\n");}. – Werner Sep 4 '13 at 23:37 You can use \textbackslash rather than $\backslash$ to keep the current font. With $..\$ you change to math font.

\texttt{This is a backslash: \textbackslash.}

• I actually noticed the the font changes from monospace to normal text when using pdftex at least. It was one of the first things I tried. – Thomas James Sep 5 '13 at 19:42
• With pdf(la)tex the symbol is not available for the standard typewriter font. I tested with lualatex and the fontspec package: \documentclass{memoir} \usepackage{fontspec} \begin{document} \noindent \textbackslash\ \ldots the backslash in roman font.\ \texttt{\textbackslash\ \ldots the backslash in typewriter font.} \end{document} – Kevin Bader Sep 6 '13 at 7:59
• This is good to know. I will start fiddling with other tex implementations. Also thank you for catching the pdf(la)tex issue! I somehow always forget that even when talking about it... which of course is bad seeing that it refers to something completely different. – Thomas James Sep 6 '13 at 13:35

or you can try: \texttt{\char\\} (for me it looks better than \texttt{\textbackslash})

• @Downvoter Please do not downvote a new user before you haven't commented and waited for a response. Now that your vote has been made please leave a comment why you did so and a proposal on how to improve the answer. – Henri Menke Aug 7 '14 at 7:52
• @ChrisPer Welcome to TeX.SX! – LaRiFaRi Aug 7 '14 at 7:55
• +1 because this is a method applicable for any ASCII character (more or less special in TeX) and usable in macro parameters (where \verb cannot be used). For example \texttt{\char\{}, \texttt{\char\^} etc. – wipet Aug 7 '14 at 8:03

\textbackslash{} looks the best choice. It may be used alone as well as in \texttt{'\textbackslash{}xAA'} (to get '\xAA'`) and alikes.