Reputation: 6783
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:
counter.exe < counter.c
15
So far the only rules I'm using are:
Only count lines that have more than 3 characters (no blank lines or lines that only have a closing brace and semi-colon, etc).
Don't count spaces as characters.
Here's my program:
#include <stdio.h>
int main() {
int input;
int linecount = 0;
int charcount = 0;
while ((input = getchar()) != EOF) {
if (input == ' ') {
}
else if (input == '\n') {
if (charcount > 3) {
linecount++;
}
charcount = 0;
}
else {
charcount++;
}
}
printf("%d\n", linecount);
return 0;
}
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?
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!
Upvotes: 2
Views: 16181
Reputation: 54811
I realise this was a programming example, but if you want to use a windows command line I found this.
Which lead to:
findstr /R /N "^" *.h *.c | find /C ":"
Counts all lines in .h and .c files.
Upvotes: 4
Reputation: 57749
Make a schedule of how long it will take you to write and debug the application. Note the ending date.
Spend some time searching the web for tools such as:
http://www.campwoodsw.com/sourcemonitor.html
Take the remaining time in your schedule and go on vacation. :-)
Otherwise the task becomes monstrous. Such as parsing comments. Defining a line (and how many statements or tokens are on a line). Are blank lines counted?
Save your precious time for other projects. Use existing tools.
Upvotes: 0
Reputation: 51565
I guess I came from a different development style than kvista, but we counted lines of code and comments separately. We expected that the comments would be a certain percentage of the total lines (comments + code). We didn't count blank lines at all.
If you're looking for a bit of a programming challenge, you can measure the cyclomatic complexity (or conditional complexity) of your C programs.
Upvotes: 1
Reputation: 5059
Generally, people do:
However, people also assume/practice:
Code line counters, as a result, generally take into account all line breaks in their computation.
Upvotes: 7