Comments in C

Comments in C

Comments in C language are use to provide information about the lines of coding stuff. It is widely used for the code documentation. In the C language, there are 2 types of comments

Comments in C
comments in c
  • Single Line Comments
  • Multi-Line Comments

Single Line Comments

Single line comments are those which are represented by double slash “\”. Let’s look at an example which shows the use of a single line comment in C

.#include<stdio.h>  
int main(){   
 //This is a single line comment       
printf("Hello C");  
  return 0;  
}    

Even you can put your comment after the statement as well.

For example:

printf("Hello C");//this is a single line comment

Mult Line Comments

Multi-Line comments are represented by slash “\” then asterisk “*” and then asterisk “*” then slash “\”.

It can occupy multiple lines of code, but cannot be nested.

Syntax:

/* multi line code to be commented */

Let’s look at an example of a multi-line comment in C.

#include<stdio.h>
  int main(){    
    /*print information  with    
  Multi-Line Comment*/     
 printf("Hello C");  
  return 0; 
 }   

Rules for Writing Comments

1. Program may include any number of comments at any place.

Example:
// header files
#include<stdio.h>
#include<conio.h>
void main(){
// variable declaration
int a,b,c;
a=10;
b=20;
c=a+b;
printf("Sum= %d",c);
getch();
}

2. Nested Comments are not possible, it means that there is no possibility for comments within comments.

Example:

void main(){
/*
/* comments */
*/
}

3. Comments can be splits over more than one line.

Example:
void main(){
/* main      function   body part*/
}

4. Comments are not case sensitive.

Example:
void main(){
/*  MAIN Function BODY   */
}

5. Single line comments start with “//”

Example:
void main(){
// Single line comment
}

Comment at End of Code Line

You can also create a comment that displays at the end of a line of code. But generally its a better practice to put code before the line of code.

Example: This example goes same for C/C++ as the commenting style remains same for both the language.

int student_id; // id of the student

When & Why is it necessary to use Comments in programming?

  • A person reading a large code would be confused if a comment about the details of the program was not provided.
  • Comments are a way to make a code more readable by providing more details.
  • Comments can make code more understandable by including a description of an algorithm.
  • If the code is to be reused after a long interval, comments can also be helpful to one’s self.

Leave a Comment