Understanding Comments in C: A Guide to Single-line and Multi-line Usage

Learn about comments in C programming, their importance in enhancing code readability, and how to use single-line and multi-line comments effectively. Discover tips for preventing code execution during testing and improving code documentation.



C Comments

Introduction to Comments in C

Comments in C are used to explain the code and make it more readable. They can also be helpful to temporarily prevent certain code from executing while testing alternatives.

Comments can either be single-line or multi-line, depending on the length of the comment you want to write.

Single-line Comments

Single-line comments start with two forward slashes (//). Any text between // and the end of the line will be ignored by the compiler and will not be executed.

Example

// This is a comment
printf("Hello World!");

In this example, the comment explains the line of code below it. The compiler ignores the comment and only executes the printf statement.

You can also place comments at the end of a line of code, like this:

Example

printf("Hello World!"); // This is a comment

Multi-line Comments

Multi-line comments begin with /* and end with */. Any text between these symbols will be ignored by the compiler.

Example

/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");

Single-line or Multi-line Comments?

It's up to you to decide whether to use single-line or multi-line comments. Typically, // is used for short comments, and /* */ is preferred for longer explanations.

Good to know: Before the C99 version of C (released in 1999), only multi-line comments were allowed in C.