# Problem with a conditional in a tabular

I want to use conditionals to fill a tabular, but it fails. My MWE:

\documentclass{article}
\usepackage{environ}

\newcounter{mycounter}

\NewEnviron{montab}{%
\setcounter{mycounter}{0}
\newcommand{\mcItem}[1]{%
\stepcounter{mycounter}%

\ifcase \arabic{mycounter} % If counter = 0
\relax
\or % If counter = 1
##1 & %
\or % If counter = 2
##1 \\%
\or  % If counter = 3
##1 &
\or  % If counter = 4
##1
\fi
}
\begin{tabular}{cc}
\BODY
\end{tabular}
}

\begin{document}

\begin{montab}
\mcItem{premier}
\mcItem{deuxieme}
\mcItem{troisieme}
\mcItem{quatrieme}
\end{montab}

\end{document}


I hoped with this code to obtain the output :

premier    deuxieme
troisieme  quatrieme


I think the problem comes from the fact for example that a part of the conditional (the \ifcase) is before a & and the rest is after it. Since any cell of a tabular forms a group, the different elements of the conditional lie in different groups.

1. Did I understand the problem correctly?
2. How to do it better? :)
-

You can't begin a conditional in one cell and end it in another one:

\usepackage{environ}

\newcounter{mycounter}

\NewEnviron{montab}{%
\setcounter{mycounter}{0}
\newcommand{\mcItem}[1]{%
\stepcounter{mycounter}%
\ifcase \arabic{mycounter} % If counter = 0
\or
\expandafter\firstoffour\or % If counter = 1
\expandafter\secondoffour\or % If counter = 2
\expandafter\thirdoffour\or  % If counter = 3
\expandafter\fourthoffour  % If counter = 4
\fi
{##1 &}{##1 \\}{##1 &}{##1}
}
\begin{tabular}{cc}
\BODY
\end{tabular}
}
\long\def\firstoffour#1#2#3#4{#1}
\long\def\secondoffour#1#2#3#4{#2}
\long\def\thirdoffour#1#2#3#4{#3}
\long\def\fourthoffour#1#2#3#4{#4}


Actually you don't need four cases, but only two, as a final \\ is good in a tabular.

\makeatletter
\newif\iffirstcol
\NewEnviron{montab}{%
\global\firstcoltrue
\newcommand\mcItem[1]{%
\iffirstcol
\global\firstcolfalse
\expandafter\@firstoftwo
\else
\global\firstcoltrue
\expandafter\@secondoftwo
\fi{##1 &}{##1 \\}}%
\begin{tabular}{cc}
\BODY
\end{tabular}}
\makeatother

-
"You can't begin a conditional in one cell and end it in another one." Inaccurate: you can't skip over & or \cr in a tabular, be it with a conditional or delimited-argument macros. However, \halign{#\cr\relax\iftrue\cr}\fi works alright, because it doesn't skip over the \cr. –  Bruno Le Floch Mar 9 '12 at 23:55
"Another noteworthy characteristic of this manual is that it doesn't always tell the truth" (The TeXbook, preface). ;-) –  egreg Mar 9 '12 at 23:59
ok, thanks fo the lessen. But, my very first attempt was done with 4 nested ifthenelse, instead of ìfcase, and this worked. Why ? –  nicolas roy Mar 10 '12 at 8:03
With nested \ifthenelse it worked because it's the same concept: resolve the conditionals before producing & or \`. –  egreg Mar 10 '12 at 9:44