HOME HTML EDITOR C JAVA PHP

C Comments: Documenting Your Code

**Comments** in C are non-executable statements used to provide explanations, notes, or descriptions within the source code. When the compiler processes your program, it simply skips over the comments, meaning they do not occupy any memory in the final executable file. Their primary purpose is to make the code more readable and maintainable for humans.

1. Why Use Comments?

Writing code is only half the battle; the other half is making sure you (or your teammates) can understand it six months later. Comments are essential for:

2. Types of Comments in C

C provides two ways to insert comments into your programs. Choosing between them depends on whether you need a quick note or a lengthy explanation.

A. Single-line Comments

Single-line comments start with two forward slashes //. Any text following these slashes on the same line will be ignored by the compiler.

#include <stdio.h>

int main() {
    // This is a single-line comment
    printf("Hello World!"); // You can also place comments here
    return 0;
}

B. Multi-line Comments

Multi-line comments start with /* and end with */. Anything placed between these two markers will be ignored, even if it spans across several lines.

/* This is a multi-line comment.
   It can span across multiple lines.
   It is very useful for explaining long algorithms. */

int x = 5; /* You can even put comments in the middle of a line */ int y = 10;

3. Best Practices for Writing Comments

While comments are helpful, over-commenting or writing poor comments can be distracting. Follow these industry-standard tips:

[Image showing the difference between good comments and bad comments in C]

4. Commenting Out Code (Debugging)

One of the most practical uses of comments is during the testing phase. If you think a specific line is causing an error, you don't have to delete it. You can simply "comment it out" to disable it temporarily.

// printf("This line will not run");
printf("This line will run");

/*
printf("None of these lines");
printf("will be executed by the compiler");
*/

5. Technical Comparison

Feature Single-line (//) Multi-line (/* */)
Scope End of the line only Until the closing marker
Standard Introduced in C99 Original C standard (C89/ANSI)
Best For Short notes Documentation / Block disabling
Warning: You cannot nest multi-line comments. For example, /* Outer /* Inner */ Outer */ will cause a syntax error because the compiler stops at the first */ it finds.