title: C Program to Count Lines of Code
body: <p>I'm writing a simple LOC counter in C to count how many lines of code are in my C source files.  It's meant to be run from the command line, redirecting the target file as input and seeing a total line count printed to standard out. For example:</p>
  
  <pre><code>  counter.exe &lt; counter.c
    15
  </code></pre>
  
  <p>So far the only rules I'm using are:</p>
  
  <ol>
  <li><p>Only count lines that have more than 3 characters (no blank lines or lines that only have a closing brace and semi-colon, etc).</p></li>
  <li><p>Don't count spaces as characters.</p></li>
  </ol>
  
  <p>Here's my program:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main() {
  
      int input;
      int linecount = 0;
      int charcount = 0;
  
      while ((input = getchar()) != EOF) {
  
          if (input == ' ') {
          }
          else if (input == '\n') {
              if (charcount &gt; 3) {
                 linecount++;
              }
              charcount = 0;
          }
          else {
              charcount++;
          }
      }
  
      printf("%d\n", linecount);
  
      return 0;
  }
  </code></pre>
  
  <p>My question is, can you offer some improvements to the rules to make this a more valid measure? Do people often count comments as valid lines of code? How about spaces or blank lines?</p>
  
  <p>I don't want to start a debate over the validity of LOC counts in general, it's something I've been asked in several interviews and I think is worth knowing, in a general sense, how many lines of code my own projects are. Thanks!</p>