[Tex/LaTex] How to put lstlisting block into subfloat block

listingssubfloats

I'm trying to compile my document but it's exploding. I've narrowed it down to this section:

\begin{figure}[h]
\caption{These are my awesome code snippets}
\subfloat[This code runs every cycle.]{
\begin{lstlisting}
    static uint64_t i = 0;
    void every_cycle()
    {
        if (i > 0)
            i--;
    }
\end{lstlisting}
}
\hfill
\subfloat[This code runs whenever.]{
\begin{lstlisting}
    uint64_t next_num()
    {
        return (i += 0x100);
    }
\end{lstlisting}
}

\label{fig:algOffset}
\end{figure}

But, when I try to compile, I get

! Argument of \lst@next has an extra }.
<inserted text> 
                \par 
l.181     }

From the lstlisting and subfloat documentation, I can't see anything I'm doing that should be disallowed. Why does this code fail to compile? Is there a better package to use than lstlisting for displaying code snippets?

Best Answer

It is possible to box the listings first, before using them in a \subfloat. Technically, this is probably similar to @Torbjørn's solution. Boxing is achieved via an lrbox environment.

enter image description here

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{subfig}% http://ctan.org/pkg/subfig
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\begin{document}

\lipsum[1]

% ======= STORE/BOX LISTINGS =======
\newsavebox{\firstlisting}
\begin{lrbox}{\firstlisting}% Store first listing
\begin{lstlisting}
static uint64_t i = 0;
void every_cycle()
{
  if (i > 0)
  i--;
}
\end{lstlisting}
\end{lrbox}
\newsavebox{\secondlisting}
\begin{lrbox}{\secondlisting}% Store second listing
\begin{lstlisting}
uint64_t next_num()
{
  return (i += 0x100);
}
\end{lstlisting}
\end{lrbox}

\begin{figure}[h]
  \caption{These are my awesome code snippets} \label{fig:algOffset}
  \subfloat[This code runs every cycle.]{\usebox{\firstlisting}} \hfill%
  \subfloat[This code runs whenever.]{\usebox{\secondlisting}}
\end{figure}

\lipsum[2]
\end{document}​
Related Question