C Language | Introduction to C | Comments
Comments let you leave notes in source code. They are ignored during compilation and do not affect the program.
Notes for Future Readers
The C sample programs in this book are only a few dozen lines long at most. The source code is kept as simple as possible and excludes unnecessary details so readers can focus on the essential principles covered in each chapter.
Real-world code, however, contains at least thousands of lines. Large development projects may contain hundreds of thousands or millions of lines. Code at that scale is difficult even for its developers to manage. You may need to read code written by someone else, and even your own code may become difficult to understand when you return to it later.
For this reason, source code can contain comments that have no effect on program execution. A C comment begins with /* and ends with */. Every character between /* and */ is removed during compilation. Because a comment may include newline characters, it can span multiple lines. Comments help explain the source code to other readers and remind you what your own code means when you revisit it later.
Code 1
#include <stdio.h>
int main()
{
/* This comment does not affect the program. */
printf("This statement is executed.\n");
/* printf("This statement is not executed because it is inside a comment.\n"); */
/*
Add supplementary explanations that make the source code easier to understand.
A comment may span multiple lines.
*/
return 0;
}
This program contains comments in its source code. Leaving explanatory comments is useful in large development projects. Note, however, that comments cannot be written inside string literals.
Comments also cannot be nested. For example, if you write /* /* */ */, only /* /* */ is interpreted as a comment.
Although not defined in the original C specification, many compilers also support single-line comments. A single-line comment starts with two consecutive slash characters, //, and continues to the end of the line.
// This is a comment.
// Its scope is one line, so each line needs its own marker.
printf("Kitty on your lap"); // A comment can also appear after code.
/////////// This is also a comment. ///////////
Single-line comments are part of the C++ language specification rather than the original C specification. However, many modern compilers support C++, so they also permit single-line comments in C code. For example, you can use one to temporarily disable a line while testing a program. If you need to write strictly portable code for an older C standard, avoid this comment style.
The C comment form /* */ and the // form added by C++ are common across many programming languages. They are used in C/C++, Java, C#, JavaScript, and other languages.