Listing with line numbers inside a table

I typeset a lot of listings (using the listings package) inside (array-based) tabular environments. This works like a charm, however, breaks when I pass the numbers= option to the listing:

\documentclass{article}

\usepackage{listings}
\usepackage{array}

\begin{document}

\begin{tabular}{p{8cm}}
% The following works if you remove the numbers=left option
\begin{lstlisting}[language=C,basicstyle=\ttfamily, numbers=left, gobble=4]
int main(){
printf("Hello, Bug\n");
}
\end{lstlisting}
\end{tabular}

\end{document}


This fails with the error message:

Runaway definition?
#1\\left\unskip \relax \@endpbox \hskip \col@sep
! Forbidden control sequence found while scanning definition of \lst@temp.
<inserted text>
}
l.9 ...sicstyle=\ttfamily, numbers=left, gobble=4]


Any idea, what causes this problem?

Is there a possible workaround (besides external boxing or falling back to \lstinputlisting)?

-
I don't know if this has side effects, but putting the environment inside braces doesn't trigger the error. –  egreg Jun 26 '11 at 21:52
@egreg: That indeed seems to solve the problem. Did you somehow figure this by looking at the source or was it just "trial-and-error"? –  Daniel Jun 26 '11 at 22:01
Why are you putting a lstlisting in a tabular float? –  You Jun 26 '11 at 22:20
Side note: If you have many same styled listings, then create proper environment for them, e.g. \lstnewenvironment{c-numbers}{\lstset{language=C,basicstyle=\ttfamily,numbers=l‌​eft,gobble=4}}{} (so you can later just type \begin{c-numbers}...\end{c-numbers}). If all of your listings have same settings, then just use once \lstset{...} in preamble of your document. –  przemoc Jun 26 '11 at 22:31
@przemoc: Right, I am using this all the time. However, both do not actually contribute to a MWE. –  Daniel Jun 27 '11 at 7:49

The problem seems to be solvable by putting the lstlisting environment in braces:

\begin{tabular}{p{8cm}}
{\begin{lstlisting}[language=C,basicstyle=\ttfamily, numbers=left, gobble=4]
int main(){
printf("Hello, Bug\n");
}
\end{lstlisting}}
\end{tabular}


It seems that without braces the macros of listings go "too far" and try to look at the internal token that finishes table cells (the TeXbook calls it \endtemplate, but it cannot really be written in any way in a document). The clue was indeed the "Forbidden control sequence found" message.

-