[SOLVED]How do you comment code ?

Thread Starter

Pushkar1

Joined Apr 5, 2021
416
I need tips to comment embedded program, How do you comment code ? If the good comment is written in the code, Then it becomes a little easier to understand someone's code.

For example I've written two comments for single line in the code. What comments would you recommend ?

C:
void main(void)
{
    
     TRISAbits.TRISA1 = 1
    // Configured Port A Pin 1 to input
    // Make Port A Pin 1 to input
    
    TRISBbits.TRISB1 = 0
    // Configured Port B Pin 1 to output
    // Make Port B Pin 1 to output
    
    while (1)
    {
        
    }
}
How to comment code so that it is easier for someone to understand code?
 

hexreader

Joined Apr 16, 2011
581
Your comments seem to state the obvious - I would have commented to show some useful information.
What you are doing is obvious. Why you are doing it, is missing

I would write something like:
Code:
void main(void)
{
    
     TRISAbits.TRISA1 = 1       // A1 set input for button 1 (low when pressed)   
     TRISBbits.TRISB1 = 0        // B1 output for error LED (lit when high)
    
    while (1);                            // loop forever to prevent exit from main

}
 

MrChips

Joined Oct 2, 2009
30,714
There is no need to comment each line as you have done.
Hardware configuration would be done in a separate function or header file.
The total HW configuration would be documented in HW specifications.
C:
void initialize_HW(void)
{
   // HW initialization
   /*----------------------------------
   PORTA7 = output = LED4
   PORTA6 = output
   PORTA5 = output
   PORTA4 = output
   PORTA3 = input   = SW2
   PORTA2 = input
   PORTA1 = input
   PORTA0 = input

   PORTB7 = output
   PORTB6 = output
   PORTB5 = output
   PORTB4 = output
   PORTB3 = input
   PORTB2 = input
   PORTB1 = input
   PORTB0 = input
   ----------------------------------*/
}

void initialize(void)
{
   initialize_HW();
}

void main(void)
{
   initialize();
   while (1)
   {
      doEvent();
   }
}
 

BobaMosfet

Joined Jul 1, 2009
2,110
I need tips to comment embedded program, How do you comment code ? If the good comment is written in the code, Then it becomes a little easier to understand someone's code.

For example I've written two comments for single line in the code. What comments would you recommend ?

C:
void main(void)
{
  
     TRISAbits.TRISA1 = 1
    // Configured Port A Pin 1 to input
    // Make Port A Pin 1 to input
  
    TRISBbits.TRISB1 = 0
    // Configured Port B Pin 1 to output
    // Make Port B Pin 1 to output
  
    while (1)
    {
      
    }
}
How to comment code so that it is easier for someone to understand code?

Generally speaking, I use C++ comment style to the right of any line I'm working with-- '//' This allows me to use C-style comments '/*' and '*/' to block out sections for debugging, etc, without modifying comments.

Beyond that, I probably comment more than most, and here is my style:

Comment block before every function/procedure:
Code:
/*****
*
*  FUNCTION_NAME    -     What function is for
*
*****
*
*   IN:     variable type     -    purpose of variable
*           ...
*   OUT:    variable type     -    purpose of variable
*
*   NOTE:  Description function, what it does, how it works.  Anything special about it
*
*****/
variable-type function_name(variable type args)
   {
   ...
   }
If the IN/OUT variable is non-existent, put 'VOID' in place of a variable type in the comment block.

I also put a good comment block at the top of the file, for example, if it's a driver, the comment block will explain everything a bout it. The accompanying header file does not need that info, as that is internal documentation.

At the end of the day, find something that works for you, and be consistent.

It might seem like a lot of work, but the discipline to do it pays great dividends down the road for ever more complex code that you write. You can get so deeply wound intellectually into writing complex logic, a state of 'flow' as we developers call it, that 10 years down the road, you won't be able to understand what magic you worked without the comments. What the code is doing specifically isn't really what comments are about- comments are about the _logic_ that the code is doing- the concept the code is trying to accomplish.

In fact, I have a boilerplate file I go to that has the basic comment format I use for C and H files, for the file header, and blocks that go beneath it so I'm always consistent.
 

Ian Rogers

Joined Dec 12, 2012
1,136
One of the idea's of C identifiers AND!! the ability to group variables, there is not normally the need to remark..

ie;-

TRISA = 3; // What's the point!!

However! Complex functions that may need revisiting I just comment the input, basic process and output..
 

click_here

Joined Sep 22, 2020
548
You want to say something that is more than the code. The code tells you that those ports are being set to input/output, not what is on the pins...
Example...
Code:
  TRISAbits.TRISA1 = 1;  // Restart push button input
  TRISBbits.TRISB1 = 0;  // Relay to motor output
But your #1 way to comment is by using self documenting code. Call your variables a name that tells the person what the code is doing(e.g. lastResetButtonState), same with function names (e.g. isPrimeNumber)

Use enums, avoid "magic numbers", ect...
 

xox

Joined Sep 8, 2017
838
Also, when using multiline comments during debugging sessions, be sure to put a line comment right before the closing */. That way, you can uncomment the entire block by simply adding a line comment before the opening /*.

Example:

Code:
/*
puts("line one");
puts("line two");
//*/
Then to uncomment the block:

Code:
///*
puts("line one");
puts("line two");
//*/
 

DickCappels

Joined Aug 21, 2008
10,152
I asked a software architect where I worked whether they could comment their code in a little more detail. His comment, which I respect was "Good code is self-commenting", meaning that a REAL software engineer would know how it worked by looking at the code and comments were not needed. After that I restricted my C programs to flow charts and state diagrams and left the coding to the REAL software engineers.

Try to find a happy compromise. You don't need to describe the entire program step-by-step but in the future little clues like
" ;save this byte for determining polarity " should come in handy.
 

click_here

Joined Sep 22, 2020
548
Because of HLL, optimizing compilers, and faster MCU instruction cycles, we can choose code readability and maintainability over code efficiency.

As an example, we can write

nrf24l01_set_ce();

instead

PORTBbits.RB3 = 1; // turn on nRF24L01 CE
Agree

Premature optimization is the footprint of a programmer that does not understand what a compiler does with their code.
 

Ya’akov

Joined Jan 27, 2019
9,071
A boiled down rule for commenting is: why not what.

The code tells you what was done, the comment needs to explain why it was done.

In general comments are only really necessary in two cases:
1) Labeling a block of related statements, such as "initialization" or "font data", etc.
2) Explaining something that can't be understood from the line itself. This could be the initialization of a constant or variable, the purpose of a function, or some "clever" hack or workaround that took time to figure out.

In the case of functions/subroutines, it is my habit to carefully document what the arguments are and what the return is.
 

Thread Starter

Pushkar1

Joined Apr 5, 2021
416
Thanks everybody for the help. The purpose of this thread is to write good comments for code

I've written comments for below code. How would you write comment for this code if you have to write comments.

C:
#define _XTAL_FREQ   20000000

#define LED  RB0  //define pin for led

#define LED_ON           1
#define LED_OFF          0

void main(void)
{
    TRISB0 = 0;  // Make RB0 pin output
    LED    = LED_OFF; // Make RB0 pin low
   
    while(1)
    {
        LED = LED_ON;  // Turn on LED
        __delay_ms(500);// Wait 500ms
        LED = LED_OFF;// Turn off LED
        __delay_ms(500);// Wait for 500ms
       
    }
  
}
 
Last edited:
1) Always "state the obvious" in your c-comments, as the intended design meaning of code is only "obvious" to the person who wrote it, not to the next person who has to understand and maintain your code.
2) C-code is not self documenting. Anyone who says it is is lying and trying to protect their own job by making sure that they are the only person who can understand the code they have written. They are toxic employees and they do not have the best interests of the company at heart. [If I hear an employee say their code is "self-documenting", I would fire them immediately before they deliberately create a ticking time-bomb of unmaintainable code.]
3) Make self-explanatory plain-English comments a requirement of the code-review process. If the reviewers can't understand what the code does from reading just the comments, then the code should fail the review.
 

MrChips

Joined Oct 2, 2009
30,714
1) Always "state the obvious" in your c-comments, as the intended design meaning of code is only "obvious" to the person who wrote it, not to the next person who has to understand and maintain your code.
2) C-code is not self documenting. Anyone who says it is is lying and trying to protect their own job by making sure that they are the only person who can understand the code they have written. They are toxic employees and they do not have the best interests of the company at heart. [If I hear an employee say their code is "self-documenting", I would fire them immediately before they deliberately create a ticking time-bomb of unmaintainable code.]
3) Make self-explanatory plain-English comments a requirement of the code-review process. If the reviewers can't understand what the code does from reading just the comments, then the code should fail the review.
I beg to disagree.

1) "state the obvious" - That is totally opposite to intuition and plain common sense.
2) My C-code is self documenting because I have developed and implemented a coding style that makes it self documenting. It is not an automatic process. With the proper use of constants and defines in header files my code can be very readable.
3) There is no need to comment lines of code. If the specifications of a program function is clearly defined then the code becomes clear.

If a code reviewer cannot understand my code I would fire the reviewer can get someone who can understand code.
 

ErnieM

Joined Apr 24, 2011
8,377
I prefer to make global self commenting labels so I need not comment what should be obvious.
C:
#define _XTAL_FREQ   20000000

#define LED  RB0  //define pin for led

#define LED_ON           1     // make pin high
#define LED_OFF          0    // make pin low
#define PIN_OUT          0    // pin is 0utput
#define PIN_IN              1    // pin is 1nput

void main(void)
{
    TRISB0 = PIN_IN;     // LED pin direction
    LED    = LED_OFF;
   
    while(1)
    {
        LED = LED_ON;  
        __delay_ms(500);
        LED = LED_OFF;
        __delay_ms(500);
       
    }
  
}
Note the only code line commented is the TRIS setting as all other lines plainly self document. Even this could be improved by adding #defines for the TRIS.
 
I beg to disagree.

1) "state the obvious" - That is totally opposite to intuition and plain common sense.
2) My C-code is self documenting because I have developed and implemented a coding style that makes it self documenting. It is not an automatic process. With the proper use of constants and defines in header files my code can be very readable.
3) There is no need to comment lines of code. If the specifications of a program function is clearly defined then the code becomes clear.

If a code reviewer cannot understand my code I would fire the reviewer can get someone who can understand code.
We will have to agree to differ on each of these points.
Your undocumented code requires the company to pay an expensive expert coder to decipher your code after you have left the company, becuase how your code works and what it does only seems obvious to you becuase you wrote it. It's intended meaning and Modus operandi cannot simply be read from the file as a there are no plain English explanatory comments.
As such I would not employ someone with your attitude to code commenting.
 

MrChips

Joined Oct 2, 2009
30,714
We will have to agree to differ on each of these points.
Your undocumented code requires the company to pay an expensive expert coder to decipher your code after you have left the company, becuase how your code works and what it does only seems obvious to you becuase you wrote it. It's intended meaning and Modus operandi cannot simply be read from the file as a there are no plain English explanatory comments.
As such I would not employ someone with your attitude to code commenting.
Thank goodness because I own my own company and I get to choose who codes for me.
 

ElectricSpidey

Joined Dec 2, 2017
2,758
I hardly ever comment code...but I'm not a professional, and 99.9999% of my code will never be seen by anybody else, and it only takes me a few seconds or a little longer to review and understand my older code. (I consider comments a form of clutter)

But, I think the proper answer here is...If you are a professional then you must comment according to what your employer requires, and not using advice from some internet strangers.
 

click_here

Joined Sep 22, 2020
548
>Always "state the obvious" in your c-comments

Terrible advice.

You are basically writting your code twice.

At the end of the week when the team leader asks why you are taking so long and you say that you were doing this...
Code:
LED = LED_OFF;  // Turn off the led
... they are not going to be happy. "Why are wasting time doing this rubbish" would be a mild reaction...

>C-code is not self documenting

That is true as the language is very large and flexible.

It takes effort to make your code self documenting, but saying that it can't be done is a massive over simplification and sounds like a cognitive bias of yours.

>They are toxic employees and they do not have the best interests of the company at heart

Again, another over simplification.

There are some coders out there that obfuscate their code to protect their job - They will also not properly train the juniors so that they remain the most competent person at a task (but this isn't unique to the programming world)

However: there are others that don't want to "teach grandma to suck eggs".

Effort in documentation should be directed into explaining algorithms.

>If the reviewers can't understand what the code does from reading just the comments, then the code should fail the review.

Shouldn't you be more worried if the code was unreadable? That's where bugs hide. What if the code differs slightly from the comments?
 

Thread Starter

Pushkar1

Joined Apr 5, 2021
416
But, I think the proper answer here is...If you are a professional then you must comment according to what your employer requires, and not using advice from some internet strangers.
BTW I'm student what is meaning of self documenting?

Code:
LED = LED_OFF;  // Turn off the led
In this example, comments is not needed here because the line itself is telling that LED is off.

Is this self documenting?
 
Top