# Cannot \newif inside a conditional

I want to create a conditional if it is not defined yet. The following is my unsuccessful attempt.

%%% in file A
\documentclass{article}

\newif\ifdraft\drafttrue

%%% in file B
\newif\ifdraft\draftfalse
\fi

\begin{document}
hello
\end{document}


Error Incomplete \ifx raises when I compile the sample code.

• Welcome to TeX.SX! Once I comment out the initial \newif\ifdraft\drafttrue this complies for me without any problems. – user30471 Sep 24 '20 at 7:16
• @Andrew I also found that. But that is exactly what I need: if file A defines \ifdraft, then file B do nothing; if file A doesn't define \ifdraft, then file B should define it. – Tianren Liu Sep 24 '20 at 7:21

If you use the LaTeX tests they take care to lift the true and false branches out of the tex primitive conditional:

%%% in file A
\documentclass{article}

\newif\ifdraft\drafttrue

%%% in file B
\makeatletter
\makeatother

\begin{document}
hello
\end{document}


Your version fails as when the conditional is defined the \ifx test is false so in

\ifx \OptionLoaded \undefined
\newif\ifdraft\draftfalse
\fi


Tex tries to skip past \newif\ifdraft\draftfalse without evaluating anything so \newif is just an inert token, however when skipping it does match \if tokens so sees \ifdraft and the \fi but it carries on skipping expecting another \fi to close the \ifx.

• +1 Perhaps in the real use-case \OptionLoaded is needed but at least in the MWE it is redundant and, instead, you could use \@ifundefined{ifdraft}{\newif\ifdraft\draftfalse}{}. – user30471 Sep 24 '20 at 7:25

As explained by David Carlisle, when TeX reads \newif\ifdraft\draftfalse, it will ignore \newif and consider \ifdraft as the opening of a conditional. Thus another workaround is to replace \ifdraft with \csname ifdraft\endcsname.

%%% in file A
\documentclass{article}

\newif\ifdraft\drafttrue

%%% in file B