About Lesson
Comment Checker C Program
Here’s a simple C program that identifies whether a given line is a comment or not. The program checks if the line starts with // for single-line comments or /* for multi-line comments.
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 256
int is_comment(const char *line) {
// Trim leading spaces
while (*line == ' ' || *line == 't') {
line++;
}
// Check for single-line comment
if (strncmp(line, "//", 2) == 0) {
return 1; // Single-line comment
}
// Check for multi-line comment
if (strncmp(line, "/*", 2) == 0) {
return 1; // Multi-line comment start
}
// Check for the end of multi-line comment
if (strstr(line, "*/") != NULL) {
return 1; // Multi-line comment end
}
return 0; // Not a comment
}
int main() {
char line[MAX_LINE_LENGTH];
printf("Enter a line of code: ");
fgets(line, sizeof(line), stdin);
// Remove newline character from input
line[strcspn(line, "n")] = '';
if (is_comment(line)) {
printf("The line is a comment.n");
} else {
printf("The line is not a comment.n");
}
return 0;
}
Explanation of the Code
- Input Handling: The program reads a line of code from the user.
- Comment Checking: The
is_comment
function checks:- If the line starts with
//
(single-line comment). - If the line starts with
/*
(beginning of a multi-line comment). - If the line contains
*/
(end of a multi-line comment).
- If the line starts with
- Output: The program informs the user whether the line is a comment or not.
How to Compile and Run
-
Save the code in a file named
comment_checker.c
. -
Open your terminal or command prompt.
-
Navigate to the directory where the file is saved.
-
Compile the program:
gcc comment_checker.c -o comment_checker
-
Run the program:
./comment_checker
-
Enter a line of code when prompted to see if it’s identified as a comment.
Example 1
Input:
Enter a line of code: Hello World
Output:
The line is not a comment.
Exercise Files