Course contentsShow
← C
Lesson 33 of 1,2191. FoundationsFree lesson

Single-line comments `//`

Single-line comments //

What you'll learn: How to leave notes for yourself and other humans within your code without the computer trying to run them as commands.

Your code's sticky notes

Imagine you are building a piece of flat-pack furniture. The instruction manual has diagrams of screws and boards, but it also has text that says, "Make sure the finished side faces out." That text isn't a physical part of the bookshelf; it’s a helpful hint to ensure you don't make a mistake.

In C, comments are those helpful hints. When you write code, you aren't just writing for the computer; you are writing for your future self and your teammates. A few weeks from now, you might look at a complex calculation you wrote and wonder, "Why did I do it this way?" Comments provide the "why."

The double slash //

The most common way to write a comment in C is by using two forward slashes: //.

When the C compiler (the tool that turns your text into a program) sees //, it ignores everything that follows it on that specific line. It treats that text as invisible whitespace. It’s like a "mute" button for the computer, but a "loudspeaker" for humans reading the file.

#include <stdio.h>

int main() {
    // This line is a comment. The computer skips it!
    printf("Hello World"); // We can also put comments at the end of a line
    
    // printf("This won't run"); 
    // The line above is "commented out," which is great for testing!

    return 0;
}

When to use them

You don't need to comment on every single line. Writing // This prints Hello next to a print command is like putting a label on a toaster that says "Toaster." It’s redundant.

Instead, use single-line comments to:

  1. Explain the "Why": Explain a choice that isn't immediately obvious.
  2. Label Sections: Use them as headers to organize your code into logical parts.
  3. Temporary Silencing: If a line of code is causing an error, you can "comment it out" by putting // in front of it to see if the rest of the program works without it.

Key takeaway

Use // to create human-readable notes that the computer will completely ignore.