[Tex/LaTex] How to expand a macro into a tabular head

macrostables

I would like to be able to define a macro that can be used in the tabular definition. How can I do this?

This does not work:

\documentclass{article}

\begin{document}
\gdef\buildtabularhead{|||}

\begin{tabular}{\buildtabularhead}
1 & 2 &3\\
\end{tabular}
\end{document}

Best Answer

This is probably not practical but it's a nice demonstration of \expandafter and gets around the problem of macros in the table preamble with the array package.

\documentclass{article}
\usepackage{array}
\begin{document}
\def\buildtabularhead{|c|c|c|}
\expandafter\tabular\expandafter{\buildtabularhead}
1 & 2 &3\\
\endtabular
\end{document}

The two \expandafters make sure that the macro \buildtabularhead is expanded before LaTeX knows it should be expecting a tabular preamble. Notice also that instead of \begin{tabular}...\end{tabular} I had to use \tabular...\endtabular. Internally the former does the same as the latter but surrounding it with a group and doing important checks, including proper nesting (See source2e Section 54.1).