Course Content
COMPILER DESIGN (CST-012) UTU
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

  1. Input Handling: The program reads a line of code from the user.
  2. 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).
  3. Output: The program informs the user whether the line is a comment or not.

How to Compile and Run

  1. Save the code in a file named comment_checker.c.

  2. Open your terminal or command prompt.

  3. Navigate to the directory where the file is saved.

  4. Compile the program:

    gcc comment_checker.c -o comment_checker
  5. Run the program:

    ./comment_checker
  6. 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
Compiler Practical 2.pdf
Size: 43.27 KB
0% Complete