2

It seems that \csname automatically defines the control sequence in question if it's not already defined. The code below creates a document creating "a b c"; swapping the \csname line and \foo line gives an error. I would have expected \csname to simply give an error if used with an undefined control sequence, but instead it appears it defines the sequence to something empty?

\documentclass{article}
\begin{document}
a
\csname foo\endcsname
b
\foo
c
\end{document}

It behaves exactly the same in pdflatex and lualatex, and with some syntactic differences the same behavior happens in pdftex and luatex as well. Is this expected behavior (and if so, where is it documented), and how can I work around it?

Kyuuhachi
  • 135

1 Answers1

4

No, the working of \csname is different from what you believe.

If the control sequence \foo is defined, then \csname foo\endcsname will be equivalent to \foo.

Otherwise, \csname foo\endcsname would (locally) define \foo as being equivalent to \relax and process it as such.

The relevant quotation from “TeX by Topic” (page 131):

enter image description here

You can do

\ifcsname foo\endcsname\csname foo\endcsname\else\ERROR\fi

to obtain the behavior you want.

egreg
  • 1,121,712
  • ...where \ERROR is just a(ny) control sequence that does not exist. – Werner Sep 10 '20 at 20:20
  • That's kinda inconvenient. I wonder why it's defined like that. – Kyuuhachi Sep 10 '20 at 20:28
  • @Caagr98 Knuth had good reasons for doing it and it's actually useful. You don't want a bunch of errors when you use \csname for a system of cross-references and the reference is not yet defined. – egreg Sep 10 '20 at 20:52
  • I suppose the intended use case is different from what I'm using it for. I still think the no-error version should be the one requiring \ifcsname, but I suppose there's no point arguing about it. – Kyuuhachi Sep 10 '20 at 21:11