# Using the tabu environment, within a conditional, within newenvironment

I am getting error messages (“Misplaced alignment tab character &.”) when I define a tabu environment within a conditional, with \newenvironment. Can this be avoided?

Here is a minimal working example:

\documentclass{article}
\usepackage{tabu}
\begin{document}

\newif\ifmyparameter
\myparametertrue

% this produces an error
\newenvironment{tableau}[1]{%
\ifmyparameter
\begin{tabular}{|lll||#1|}
\else
\begin{tabular}{|rrr||#1|}
\fi%
}{\end{tabular}}

% but it works if there is no conditional
%\newenvironment{tableau}[1]{%
%                   \begin{tabu}{|lll||#1|}
%               }{\end{tabu}}

% it also works if I use a tabular environment instead of tabu
%\newenvironment{tableau}[1]{%
%               \ifmyparameter
%                   \begin{tabular}{|lll||#1|}
%               \else
%                   \begin{tabular}{|rrr||#1|}
%               \fi%
%               }{\end{tabular}}

\begin{tableau}{c|c|c}
a & b & c & d & e & f \\
c & d & e & f & g & h\\
\end{tableau}

\end{document}


One way around this is to place the entire \newenvironment command within a conditional. This compiles without an error, but it requires a lot of duplicate code to have two complete definitions of the new environment (i.e., in the real-world application, not just the MWE).

\documentclass{article}
\usepackage{tabu}
\begin{document}

\newif\ifmyparameter
\myparametertrue

\ifmyparameter
\newenvironment{tableau}[1]{%
\begin{tabu}{|lll||#1|}
}{\end{tabu}}
\else
\newenvironment{tableau}[1]{%
\begin{tabu}{|rrr||#1|}
}{\end{tabu}}
\fi%

\begin{tableau}{c|c|c}
a & b & c & d & e & f \\
c & d & e & f & g & h\\
\end{tableau}

\end{document}


The problem is that you have to get rid of \fi before starting the tabular/tabu environment. See What do \@firstoftwo and \@secondoftwo do? for more information.

\documentclass{article}
\usepackage{tabu}

\newif\ifmyparameter
\myparametertrue

\makeatletter
\newenvironment{tableau}[1]{%
\ifmyparameter
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{\begin{tabu}{|lll||#1|}}
{\begin{tabu}{|rrr||#1|}}%
}{\end{tabu}}
\makeatother

\begin{document}

\begin{tableau}{c|c|c}
aaaa & bbbb & ccccc & dddd & eeee & ffff \\
c & d & e & f & g & h\\
\end{tableau}

\bigskip
\myparameterfalse

\begin{tableau}{c|c|c}
aaaa & bbbb & ccccc & dddd & eeee & ffff \\
c & d & e & f & g & h\\
\end{tableau}

\end{document}