Comments In C | Types, Rules & Uses Explained (+Code Examples)
Table of content:
- What Are Comments In C & Why Use Them?
- Types Of Comments In C Programming Language
- Single Line Comments In C Programming
- Multi-Line Comments In C Programming
- Rules For Writing Comments In C Language
- Advantages Of Commenting In A Program
- What Does Compiler Do With Comments In C Programs?
- Conclusion
- Frequently Asked Questions
Have you ever wondered how complex, critical, logical code is easily understood by users and developers? Or how do developers collaborate to draft efficient, bug-free code? Have you noticed the text lines within the code that are marked with delimiters like double forward slash (//) and or asterisk slash (/*)?
These are called code comments and play a crucial role in code documentation. Every language has some basic syntax to include comments in the code. In this article, we will focus on comments in C language, their types, why they are important, and how to use them, with the help of detailed explanations and examples.
What Are Comments In C & Why Use Them?
As we've mentioned before, comments play a crucial role in documenting the code. Comments in C programs are special blocks or lines of explanatory text typically used to provide annotations within a C programming source code.
A unique feature of comments is that they are not compiled when you run a C program or are considered an executable part of the program by the compiler. Hence, they do not affect any behavior or functionality of the program. Comments are solely intended for human users and developers for their understanding and maintenance of the code.
Types Of Comments In C Programming Language
There are two major types or categories of comments in C:
- Multi-line Comments (/* and */)
- Single-line Comments (//)
Note that C enabled the use of only multi-line comments until the C99 version, which is why they are often referred to as C-style comments. It was with the release of this version that the use of single-line comments first came into existence.
Single Line Comments In C Programming
As the name suggests, the single-line comments in C imply that these comments last up to only one line or a single line in practice.
- The text followed by a double slash/ double forward slash [//] in a code is considered a single-line comment.
- This means the C compiler ignores all the text after delimiter (//) during the compilation process.
These comments are typically used to give the developer an understanding without altering any code's functionality.
Syntax For Single Line Comments In C
// The comment
Here, the comment is written after the double slash delimiter, and it lasts only for that line.
Examples Of Single Line Comments In C
Look at the simple C program example below to understand the implementation of single-line comments.
Code Example:
Output:
Hello, world!
Explanation:
In the simple C code example, we include the header file <stdio.h> for input/ output operations.
- Then, we initiate the main() function, the entry point for the program's execution.
- In main(), we use the printf() function to display a string message- "Hello, world!" to the console.
- As you can see, we have used a single-line comment- "//print Hello World to the screen" which the compiler ignores. The purpose of this comment is to simply explain to the user that the printf() function is used to display- 'Hello, world!'.
- Lastly, the function closes with a return 0 statement indicating successful execution.
This was a straightforward and basic C program example showing the use of single line comments. Let's look at another example.
Code Example:
Output:
The sum of 5 and 10 is: 15
Explanation:
In the C code example, we showcase the use of single-line comments in greater detail.
- In the main() function, we declare and initialize two variables, a and b, with the values 5 and 10.
- The comment line '// Declare and initialize variable a of integer type' informs the reader that we are declaring and initializing a variable a which of integer data type.
- The comment line '// Creating a variable named b and assigning integer value 10 to it' is a variation again meant to inform the reader about what is happening in the respective line of code.
- Next, we use the addition arithmetic operator to add the values of variable a and b, and store the outcome in variable sum. We have explained the same in the code comment- '// Add a and b and store the value in a variable called sum'.
- After that, we use the printf() function to display the individual values and their sum with a descriptive message. We have mentioned the same in the comment before the line of code.
- Alternatively, we could also include information like the use of %d format specifier as a placeholder for integer values and the newline character/ escape sequence (\n) to shift the cursor to the next line.
The idea is to use comments as human-readable explanations within the code. This is to provide information about what is happening in a respective line of code, to make it easier for readers and other developers to understand the code.
Multi-Line Comments In C Programming
Multi-line comments refer to those lines of text/ comments which can span multiple lines of code, as against the single line comments which can last for only one line in code. As mentioned before, they are known as C-style comments since we could use only this types of comments in C programs up until C99 standard.
- C-style comments are enclosed between two delimiters: /* marks the start, and */ marks the end.
- These comments can also be called descriptive comment blocks or block comments.
Note that the syntax for multi-line comments varies across programming languages, and some languages might not support them at all. However, languages such as C++, Java, JavaScript, and Swift share the same C-style comment syntax.
Syntax For Multi-line Comments In C
/* comment starts
Line 1
Line 2
…
Comment ends */
Examples Of Multi-Line Comments In C
Look at the C program example below, which illustrates the basic use of multi-line or block comments.
Code Example:
Output:
Enter the age: 24
Age= 24
Explanation:
In the example C code, we begin with a multi-line or C-style comment explaining the program's purpose: take user input for the age variable and display the same to the console using printf(). The comment is enclosed between /* and */, which tells the compiler to ignore everything within these markers. Here is what is going on in the code:
- We declare an integer type variable with name/ identifier age in the main() function.
- Then, we prompt the user to enter a value for age using the printf() function.
- Next, we read the input using scanf() and store it in the respective variable using the address-of operator (&).
- After that, we use another printf() statement to display the age to the console.
Ideally, you should use comments to include relevant information to help your reader understand and work with your code. In the example above, we gave a gist of the program's purpose. Let's look at another example C program showcasing the use of multi-line comments.
Code Example:
Output:
20
Explanation:
In the C code sample, we have used two multi-line comments.
- We use the first comment to provide general information about the main() function. This can be useful for novice coders or readers.
- In the 2nd multi-line comment, we explain the program logic to help users understand the code better.
- We also have a single-line comment in the middle to describe the integer variable k.
Notice how the compiler ignores everything within the multi-line comment blocks, even though they span multiple lines and have line breaks, punctuations, etc.
This shows that you can combine both single-line and multi-line comments in C programs. Multi-line comments are helpful for explaining larger blocks of code and providing detailed descriptions that enhance code readability. Regardless of the length, anything inside /* */ is ignored by the compiler and does not affect the code execution.
Check out this amazing course to become the best version of the C programmer you can be.
Rules For Writing Comments In C Language
It is important to follow certain guidelines when writing comments in C to ensure they are beneficial for both developers and users. Below are some key rules to follow when commenting in C code:
- Ensure Appropriate Syntax: In C, single-line comments are written using the double forward slash (//), while multi-line comments are enclosed in delimiters /*...*/. It is crucial to use the correct language syntax to avoid syntax errors or unintended issues in your code.
- Be Precise and Relevant: Avoid overly long sentences. Comments should focus on explaining complex algorithms or logic that might not be easily understood at first glance. Keep them brief and to the point.
- Keep Comments Clear and Understandable: Be clear about what should be commented on, and use simple, descriptive language. Avoid comments that may confuse readers and focus on explaining the code's purpose, functionality, and any conditions or limitations.
- Use Proper Grammar and Avoid Redundancy: Check for grammar and spelling errors to ensure clarity. Avoid explaining trivial details that are obvious from the code itself, as this can lead to redundant comments that waste time and distract from the core logic.
- Keep Comments Updated: As code evolves, comments may become outdated. It's important to regularly update comments to ensure they remain accurate and relevant to the current state of the code.
- Be Mindful of Sensitive Information: Do not disclose sensitive or personal information in comments. It is the coder's responsibility to ensure comments only provide safe and necessary information.
Examples For Comments In C
Let's look at a few sample C programs/ snippets illustrating the rules and guidelines we discussed above.
Code Snippet 1:
/*
Function: add
Adds two numbers and returns the result.
Parameters:
x - First number (int)
y - Second number (int)
Returns:
The sum of x and y (int)
*/int add(int x, int y) {
return x + y;
}
Explanation:
The multi-line comment at the beginning of the code snippet above explains the everything about the add() function we are definition including its logic, parameters, and return value. Each line of the comment provides useful information about the function's role in the program, whose function definition is given later. This helps readers understand the logic with ease.
Code Snippet 2:
int m = 40; // Initialize variable m with value 40
// The following code block is used for error handling
if (m > 50) {
// Handle error
}
Explanation:
In the snippet above, we use single-line comments to explain the various steps in the program. The first comment describes the variable initialization, the next describes the purpose of a block of code, and the last one marks the place where the error handling happens. Collectively, the comments explain that the code snippet is intended for error handling, helping the programmer understand the purpose in a step-by-step manner.
Code Snippet 2:
// TODO: Implement error checking for the input values
int n = 50; // Initialize variable n with value 50
Explanation:
Here, the TODO keyword in the first comment is a reminder for the reader or programmer to carry out error checking in the future/ after input values.
These rules and examples highlight the importance of writing effective comments in C programming. Well-written comments not only enhance code readability but also promote collaboration, debugging, and maintainability.
Hone your coding skills with the 100-Day Coding Sprint at Unstop and claim bragging rights now!
Advantages Of Commenting In A Program
Adding comments in C programs not only makes it easier to understand but also offers several key benefits, including:
- Enhance Code Readability: As the comments provide a contextual understanding of the program, the logic, and the functionality, it makes it easier for the developer and the user to review the code.
- Better Maintenance and Debugging: Proper commenting generates well-documented codes that make it easier for developers to understand changes and analyze complex logic. They also assist in identifying and fixing bugs and aid the troubleshooting process.
- Knowledge Sharing and Collaboration: Comments in C programs act as learning tools for beginners and junior developers. Properly written comments help a broader section understand the program and gain critical/ complex logic insights. In other words, they facilitate knowledge sharing and collaboration among teams, making code review and decision-making processes more efficient.
- Code Reusability: We can use comments in C program to indicate which code segments are reusable, reducing the time and effort required for future development.
What Does Compiler Do With Comments In C Programs?
Comments are written as human-readable text or documentation blocks within the source code and are entirely ignored by the compiler during code compilation.
Comments in C prgorams are treated as white spaces by the compiler and are not translated into machine language or included in the object code. Meaning, no machine instructions are generated for the comments, ensuring they do not affect the functionality of the program.
Looking for mentors? Find the perfect mentor for select experienced coding & software experts here.
Conclusion
Comments in C language refer to a set of lines within the code that are not compiled/ executed, i.e., non-executable lines. The primary purpose of these comments is to aid users and developers in understanding code functionalities, logic, and algorithms.
- There are two types of comments in C language: single-line (//) and multi-line comments (/*...*/), each with a prescribed syntax.
- You must take note of a few guidelines when using comments in C programs, such are writing crisp, descriptive and relevant comments.
- Adhering to proper commenting practices offers numerous advantages, such as improved readability, maintainability, and reusability of code.
Comments also serve as effective documentation, making the code more accessible to others and fostering collaboration. Overall, commenting is a highly valuable practice for writing clear, efficient, and well-documented code.
Also Read: 100+ Top C Interview Questions With Answers (2024)
Frequently Asked Questions
Q1. Does C allow comments at the end of code lines?
Comments at the end of code lines mean writing code after a line of code. The C language allows comments to be written at the end of code lines as long as they are written using the prescribed syntax, i.e., delimiters. For example, you can place single-line comments using // at the end of a line.
Q2. What are single-line and multi-line comments in C?
Single-line comments are the comment lines confined to one line of code in a C program. We use the double forward slash as a delimiter to mark these comments.
In contrast, multi-line comments are typically a block of text lines that may extend for multiple lines (more than one line) of code as explanatory comments. They are enclosed in the /*...*/ delimiters.
Q3. How to write "single-line" comments and "multi-line" comments in C?
- Single-line comments: These comments in C follow a pair of double forward slashes (//).
Example: // This is a single-line comment. - Multi-line comments: These comments are enclosed between a forward slash followed by an asterisk at the start and an asterisk followed by a forward slash at the end.
Example: /* This is a multi-line comment */.
Q4. Can comments be nested in C?
No, we do not have nested comments in C language. If you attempt to nest comments, the compiler will throw an error. If you want to write comments that span multiple lines, it is best to use multi-line comments.
Q5. How do SQL comments differ from C comments?
- Single-line comments in SQL: These comments begin with a double hyphen (--) as against the double forward slash in C.
Example: -- This is a single-line comment in SQL. - Multi-line comments in SQL: The syntax for multi-line comments in C and SQL is the same, and they are enclosed in /*...*/.
Example: /* This is a multi-line comment in SQL,
but the syntax is the same as in C. */
Q6. What is the difference between a multi-line string and a multi-line comment?
The difference between multi-line string and multi-line comment comes from the syntax and the execution.
- A multi-line string is declared within double quotes, i.e., ("..."). And anything written inside these quotes is executed.
- Multi-line comments, on the other hand, are enclosed between slash asterisk and asterisk slash delimiters, i.e. within /*…*/. Anything written in between these delimiters is not executed by the compiler.
Q7. What is the purpose of multi-line comments in C?
Multi-line comments in C are used to explain complex logic or algorithms across multiple lines. They must be placed between /*...*/ to instruct the compiler to treat them as non-executable.
Here are a few more topics you must explore:
- 6 Relational Operators In C & Precedence Explained (+Examples)
- Pointers In C | Ultimate Guide With Easy Explanations (+Examples)
- Arrays In C | Declare, Initialize, Manipulate & More (+Code Examples)
- Control Statements In C | The Beginner's Guide (With Examples)
- Constant In C | How To Define, Rules & Types (+Detailed Examples)
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment