From Basics to Advanced Tips: Your Guide to Effective C Comments
C programming comments are essential building blocks for writing clean, readable, and maintainable code. They play a crucial role in clarifying the purpose of code sections, enhancing understanding for both programmers and the compiler (in certain cases).
Comments can be singled-lined or multi-lined.
Usinga single-line comment before a line of code on C:
In C programming, single-line comments are a valuable tool for annotating and explaining your code. Here's a breakdown of how they work: (//).Any text between // and the end of the line is ignored by the compiler (will not be executed).
This example uses a single-line comment before a line of code on C:
Example
Comments in C
#include <stdio.h>
int main() {
// This is a comment
printf(printf("Hello CodeLines.");
return 0;
}
Output
Hello CodeLines!
This example uses a single-line comment at the end of a line of code:
Example
#include <stdio.h>
int main() {
printf("Hello CodeLines!"); // This is a comment
return 0;
}
Output
Hello CodeLines!
Multi-line Comments in C Programming
Multi-line comments are essential for documenting and explaining blocks of code in C programming.
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Example
#include <stdio.h>
int main() {
/* The code below will print the words Hello How Are You! to the screen, and it is amazing */
printf("Hello CodeLines!");
return 0;
}
Output
Hello CodeLines!
Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments, and /* */for longer.
Good to know: Before version C99 (released in 1999), you could only use multi-line comments in C.