From the course: C Programming Basics: Flow Control, Variables, and Pointers

Adding comments to the code

- [Instructor] When you need to write notes to yourself, or include an explanation for others in your source code, you create a comment. Comments aren't compiled, so you're free to put anything in a comment, but you must know the rules for formatting a comment. I'm going to add a line at the tippy top of this source code file. Traditional C comments are enclosed with two characters, the slash and the asterisk. I'm going to type the slash and the asterisk to start the comment. And here, in the Code Blocks Editor, you see that the entire source code is color coded as a comment. That's because the slash asterisk characters start a comment, but I've not yet included the characters that end the comment. Now I'm going to type the comment text. For this source code file, I'll put my name and the date. To end the comment, type the asterisk and slash, the reverse of the character pair used to start the comment. And as you close the comment, you see that the editor rehighlights the rest of the source code, and leaves only the comment highlighted in gray. I'm going to save the changes. Build and run. The output is unaffected by the comment text. Comments can also span multiple lines, so I can split my comment between the name and the date. As long as the comment is embraced by the slash asterisk and asterisk slash characters, the text between them is ignored by the compiler. A second way to comment is to use two slashes. This comment works only for a single line, ignoring any text that appears after the two slashes. You can set the two slashes anywhere, not necessarily at the start of the line. As with traditional C language comments, use the double slash to write a note to yourself, or you can use it to comment out part of your code, checking for errors to disable part of the code. For example, I'm going to comment out line seven. Click the mouse at the start of the line and type the two slashes. See how the text color changes in the editor? Only the single line is a comment. Save. Build and run. Because the first put statement is disabled in a comment, it generates no output. Programmers can get really fancy with their comments. In this source code file, I've embellished the original code with some extravagant comments. These may seem silly for a short program, but for source code files that span hundreds of lines, they become visually helpful and informative. Comments are optional. I use them, and you should too if you want to take a well-documented road toward becoming a good C programmer.

Contents