# How to put source code in a LaTeX table?

I am comparing source in a paper and I would like to put them in a table, so the differences are easily spotted. I used the following LaTeX code:

\begin{tabular}{ | l | l | l |}
Option 1  &  Option  2 & Option 3 \\
\begin{lstlisting}
Code A
\end{lstlisting} &
\begin{lstlisting}
Code B
\end{lstlisting} &
\begin{lstlisting}
Code C
\end{lstlisting} \\
\end{tabular}


When compiled, this becomes a mess, so that is why I would like to know what I can do to improve the outcome.

• Hi, welcome to TeX.SX. Your code snippet, when inserted in a minimal document, does not produce any mess. Can you expand your code to a complete, compilable example (starting with \documentclass, ending with \end{document}) that demonstrates the issue? – Torbjørn T. Nov 10 '13 at 17:59
• If your snippets are one-liners, I would also consider \lstinline. Also, instead of a tabular, have you considered multicol? – Sean Allred Nov 10 '13 at 18:53
• It's not the format you'd specifically asked for, but it may be worth using if you can live with comparing two blocks of code: diff and Is there a ready solution to typeset a diff file? or Highlighting a .diff file – Mike Renfro Nov 10 '13 at 19:46

In addition to what said by David in his answer, you need to set breaklines=true otherwise the whole thing can become a mess if you have long lines.

For example, the following MWE (with that option set)

\documentclass{article}
\usepackage{listings}

\lstset{
language=C,
basicstyle=\small,
breaklines=true
}

\begin{document}

\noindent
\begin{tabular}{|p{3.6cm}|p{3.6cm}|p{3.6cm}|}
Option 1  &  Option  2 & Option 3 \\
\begin{lstlisting}
#include <stdio.h>

int main()
{
printf("Hello world\n");
}
\end{lstlisting}&
\begin{lstlisting}
#include <stdio.h>

int main()
{
printf("Hello world\n");
}
\end{lstlisting}&
\begin{lstlisting}
#include <stdio.h>

int main()
{
printf("Hello world\n");
}
\end{lstlisting}
\end{tabular}

\end{document}


yields

while, without that option, the output is

l is a single line cell set to its natural width. You want each cell to be a parbox so use p{5cm} or some other suitable length, then the cell can contain display material such as a listing.