C Comments

1. What are Comments?

  • Comments are notes written in the code that are ignored by the compiler.

  • They are used to explain code, make it readable, or temporarily disable code.

  • Comments do not affect the program execution.


2. Types of Comments in C

C supports two types of comments:

(a) Single-line Comment

  • Starts with //

  • Everything after // on that line is ignored by the compiler.

Example:

#include <stdio.h>

int main() {
int age = 25; // This is the age of the user
printf("Age: %d\n", age);
return 0;
}

Output:

Age: 25

The comment // This is the age of the user is ignored by the compiler.


(b) Multi-line Comment

  • Starts with /* and ends with */

  • Can span multiple lines.

Example:

#include <stdio.h>

int main() {
/* This program prints
the age of the user.
Multi-line comment example */

int age = 25;
printf("Age: %d\n", age);
return 0;
}

Output:

Age: 25

3. Uses of Comments

  1. Explain code for yourself or others.

  2. Temporarily disable code for testing:

// printf("This line is commented and won't run\n");
  1. Document complex logic or algorithms.


4. Best Practices

  • Write clear, concise comments.

  • Avoid obvious comments like int x = 10; // assign 10 to x (the code is self-explanatory).

  • Use comments to explain why, not what.


5. Quick Example Combining Both

#include <stdio.h>

int main() {
// Declare and initialize variables
int a = 5, b = 10;

/* Print the sum of a and b
Using printf function */

printf("Sum: %d\n", a + b);

return 0;
}

Output:

Sum: 15

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *