How do I define a \ifcommand only if it is not already defined?

For example:

\makeatletter
\@ifundefined{ifSomething}{%
  \newif\ifSomething
  \Somethingtrue
}{}
\makeatother

\@ifundefined generates the macro name from the argument string and tests, whether the command is undefined (or \relax). This removes the \if... token from the test. Also the branching is syntactically realized via arguments and not by \if...\else...\fi. Therefore an defined or undefined \ifSomething does not cause trouble for \@ifundefined.

However, there is a case, where \ifSomething after \newif in the argument can cause trouble, when the whole construct is inside a \if/\else branch. Then the trick is \csname:

\makeatletter
\@ifundefined{ifSomething}{%
  \expandafter\newif\csname ifSomething\endcsname
  \Somethingtrue
}{}
\makeatother

The etoolbox package has \providebool:

\documentclass{article}
\usepackage{etoolbox}

\newif\ifSomething

\providebool{Something}
\providebool{SomethingElse}

\begin{document}

\texttt{\meaning\Somethingtrue}

\texttt{\meaning\SomethingElsetrue}

\end{document}

enter image description here

Tags:

Conditionals