[texhax] \newif, \csname and \endcsname

Paul Isambert zappathustra at free.fr
Mon Jan 31 10:20:16 CET 2011


Le 31/01/2011 08:47, Uwe Lueck a écrit :
> "Vafa Khalighi"<vafakhlgh at gmail.com>, 31.01.2011 08:14:15:
>> \documentclass{article}
>> \newif\ifok
>> \newif\ifnotok
>> \newcommand{\printtest}{%
>> \csname ifok\endcsname\csname ifnotok\endcsname print test\fi\fi}
>> \begin{document}
>> This is a test
>> \printtest
>> \end{document}
>>
>> Tex complains that there is an "Extra \fi", why?
> Nice little study. \newif\ifok performs \let\ifok\iffalse. Therefore. \csname ifok\endcsname expands to an alias of \iffalse, therefore \csname ifnotok\endcsname is not expanded, so TeX is not aware of another \if..., TeX just tries to find an \else or a \fi matching \ifok. The first matching \fi is the first \fi. Then TeX finds the second \fi, and TeX cannot remember any \if... matching the second \fi -- this is what it is telling you.

Nice little studies of those good old conditionals indeed. There's a 
rule of thumb with them: all \fi (and \else) should be matched 
immediately by a \if..., where matched immediately means that the \if... 
doesn't need expansion to show up. The reverse is true: any \if...should 
be matched immediately by a \fi. Which is why the following are both 
incorrect in TeX:

\iffalse \let\foo\fi \fi
\iffalse \let\iffoo\iftrue \fi

or nastier -- you think you're clever, you have hidden your \iftrue! (I 
made that mistake some days ago, for some reason I didn't want to use a 
\newif):

\iftrue
     \expandafter\let\expandafter\iffoo\csname iftrue\endcsname
\else
     \expandafter\let\expandafter\iffoo\csname iffalse\endcsname
\fi

Best,
Paul


More information about the texhax mailing list