Comments in C

Comments are notes written inside a program to explain the code. They are ignored by the compiler and do not affect program execution.

Why Are Comments Important?

Types of Comments in C

1. Single-line Comment  
2. Multi-line Comment

1. Single-line Comment

Begins with // and continues till end of line.

#include <stdio.h>

int main() {

    int a = 10;   // this is a single-line comment

    printf("Value: %d", a);

    return 0;
}

2. Multi-line Comment

Starts with /* and ends with */. Used for long explanations.

#include <stdio.h>

int main() {

    /* This is a multi-line comment.
       It can span across multiple lines.
       Used to explain big concepts. */

    printf("Hello World!");

    return 0;
}

Where Should You Use Comments?

Practical Example 1 – Explaining Code

#include <stdio.h>

int main() {

    int n = 5;

    // Printing numbers 1 to 5
    for(int i = 1; i <= n; i++) {
        printf("%d ", i);
    }

    return 0;
}

Practical Example 2 – Block-wise Explanation

#include <stdio.h>

int main() {

    /* Declare variables */
    int x = 10;
    int y = 20;

    /* Calculate sum */
    int sum = x + y;

    /* Display output */
    printf("Sum = %d", sum);

    return 0;
}

Practical Example 3 – Disabling Code Using Comments

#include <stdio.h>

int main() {

    int x = 10, y = 5;

    // printf("This line is disabled temporarily\n");

    printf("Active Output: %d", x + y);

    return 0;
}

Practical Example 4 – Header Documentation

/*
    Program: Adding Two Numbers
    Author : Sourav
    Date   : 2025-01-01
*/

#include <stdio.h>

int main() {
    int a = 10, b = 20;
    printf("Sum = %d", a + b);
    return 0;
}

Best Practices for Comments

Practice Questions

  1. What are comments? Why are they used?
  2. Difference between single-line and multi-line comments.
  3. Write a program with both types of comments.
  4. Explain 4 best practices for comments.
  5. Write comments for a program that calculates the area of a rectangle.

Practice Task

Write a program to print your name and course using two single-line comments and one multi-line comment.