[Tex/LaTex] newcommand does not work with \fi

conditionalsmacros

I tried the command \newcommand{\fistudenti}{\fi} but it seems to work properly only in some cases. Here below there are two insances when it works and when it does not:

WORKS:

\documentclass[0pt]{book}
\usepackage[english]{babel}
\def\PentruStudenti{1}
\newcommand{\fistudenti}{\fi} 
\begin{document}              
\if\PentruStudenti1
show
\fistudenti
\end{document}   

But if I put \PentruStudenti{0} it does not work:

\documentclass[0pt]{book}
\usepackage[english]{babel}
\def\PentruStudenti{0}
\newcommand{\fistudenti}{\fi} 
\begin{document}              
\if\PentruStudenti1
show
\fistudenti
\end{document}   

Where do I do the mistake?

Best Answer

The conditional primitives \if.., \else and \fi need to be directly visible by TeX and can not be hidden inside macros. If TeX finds a false \if.. clause it looks at all following tokens until it finds a token equal to \else or \fi without expanding macros. If it finds another \if.. conditional it increases an internal counter and will look for the \fi for this conditional before looking for the outer one.

If you have a macro like \newcommand{\fistudenti}{\fi} the \fi is hidden and not found. The same is true for own \if.. macros inside a false clause. Both will work in a true clause because there macros are expanded as normal.

To make your macro work you need to use \let\fistudenti\fi instead, which makes \fistudenti a token identical to \fi. This is also the way used by \newif to define now conditionals. The \xxxtrue and \xxxfalse macros defined by it simply include \let\ifxxx\iftrue or \let\ifxxx\iffalse.

For further reading have a look at the Q&A What is an \if?.

Related Question