Comments in C

Sunny Bhaskar

10/27/20241 min read

In C programming, comments are non-executable statements that are used to explain and annotate the code. They help in making the code more understandable to other programmers (or even yourself) when you review it later. Comments are ignored by the compiler during the compilation process, meaning they do not affect the program’s execution.

Types of comments in C

1. Single-Line Comments

A single-line comment starts with two forward slashes (`//`). Anything after the `//` on the same line is considered a comment and is ignored by the compiler.

Syntax

// This is a single-line comment

int x = 5; // This comment explains that x is initialized to 5

Everything after `//` is treated as a comment and ignored.

2. Multi-Line Comments

Multi-line comments start with `/*` and end with `*/`. They can span multiple lines and are useful for longer explanations or for temporarily disabling blocks of code.

Syntax

/*

This is a multi-line comment.

It can span multiple lines.

*/

int y = 10;

/*

You can also use it to comment out code

int z = 15;

*/

Everything between `/*` and `*/` is treated as a comment and ignored by the compiler.

Key Points

Single-line comments are suitable for brief remarks or annotations.

Multi-line comments are useful for more detailed explanations or for temporarily removing sections of code during debugging.

C does not allow nested multi-line comments. This means that `/* /* / /` will cause an error.

Example

#include <stdio.h>

int main() {

// This is a single-line comment

/*

This is a multi-line comment.

It spans multiple lines.

*/

int a = 5; // a is initialized to 5

int b = 10; /* b is initialized to 10 */

// Printing the sum of a and b

printf("Sum: %d", a + b); // Output: Sum: 15

return 0;

}

Comments are essential for code readability and maintainability. They help others understand your code logic and make it easier for you to remember the purpose of different parts of your program when you revisit it later.

Address

Prayagraj Phaphamau

Contacts

7518998334
sunnygamingyt298@gmail.com

Subscribe to our newsletter