When programs are complex, or perform a task in an unusual way, it can be helpful to leave notes to ourselves within the program explaining what the instructions are intended to achieve. Then, when we look back at a program at a later date we can more easily understand what the program was designed to do, without having to read through it line by line attempting to follow the logic.
The notes left in programs are called comments. When the compiler encounters a comment instead of an instruction, it simply ignores it and compiles the program as if the comment wasnt there. There are two ways of telling the compiler that something is a comment and not an instruction. The first is to use the symbol // which is two / symbols back to back. It looks like this:
//This is a comment
When we mark a comment in this way, the compiler ignores everything from the // symbol to the end of the line. The compiler will then carry on compiling from the next line (unless of course that line is another comment). The second way is to mark the start of a comment with the symbol /* and mark the end of the comment with the symbol */. It looks like this:
/*This is
also a
comment*/
This has the advantage that the comment can span multiple lines, and gives us lots of room to communicate in. We can have as many comments of each type as we like in our programs, but the one rule is that we cant put multiple line comments inside other multiple line comments. So the compiler would tell us there is an error in the following program section:
/* This /*is a*/ comment*/
Comments also come in useful when we quickly want to try our program without some of the instructions weve already typed in. If we mark an instruction as a comment and compile the program, the compiler will ignore the instruction we marked. Then when we remove the comment symbols and compile again the program will be back the way it was. Programmers call this commenting-out an instruction. For example:
frogUp(1);
//frogRight(1);
frogDown(1);
Compile and run the program. Note how comments are ignored when the program is run
Try commenting out the lines identified by the comments in the program. Note how those instructions are no longer performed when the program is compiled and run again