3 of 10
added 83 characters in body
jub0bs
  • 54190
  • 17
  • 183
  • 273

You think too complicated.

Below I defined two list styles, where the first is loaded by the second, and then the comment definitions are overwritten with the invisible variants.

enter image description here

\documentclass{article}

\usepackage{xcolor}
\definecolor{commentcolor}{gray}{.5}
\definecolor{rulecolor}{named}{black}

\usepackage[T1]{fontenc}
\renewcommand{\ttdefault}{pcr}

\usepackage{listings}
\lstdefinestyle{c_with_comments}%
{
  basicstyle   = \ttfamily,
  language=c,
  morecomment  = [l]{//},
  morecomment  = [s]{/*}{*/},
  frame        = single,
  commentstyle = \itshape\color{commentcolor},
  rulecolor    = \color{rulecolor},
  breaklines,
}
\lstdefinestyle{c_without_comments}%
{
  style=c_with_comments,
  morecomment  = [il]{//},
  morecomment  = [is]{/*}{*/},
}

\usepackage{filecontents}
\begin{filecontents*}{sample.c}
#include <stdio.h> 
/*
 block comment taking up white space
*/
main()
{
    float fahr, celsius;
    float lower, upper, step;
    lower   = 0;    /* lower limit of temperature scale */
    upper   = 300;  // upper limit
    step    = 20;   // step size
    celsius = lower;
    printf("\nCelsius\tFahr\n");
    while (celsius <= upper)   
    {
        fahr = (9.0/5.0) * celsius+32.0;
        printf("%3.0f\t%6.1f\n", celsius, fahr);
        celsius = celsius + step;
    }
}
\end{filecontents*}

\begin{document}
\lstinputlisting[caption={with comments},style=c_with_comments]{sample.c}
\lstinputlisting[caption={without comments},style=c_without_comments]{sample.c}
\end{document}

I myself had to search for first, but here a cite from listings documentation:

Eventually, you might want to use the prefix i on any comment type. Then the comment is not only invisible, it is completely discarded from the output!

Speravir
  • 18086
  • 13
  • 70
  • 125