# How to understand the code which wrote by someone??

This topic is 4168 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am studying basic C/C++ almost all topics... and try to testing myself by picking up the source code from web to see the codes line by line for making understanding the code. But, I am got a problem. Many times I can not understanding or clear the code to see how the code working even I think I have enough basic to figure out the code. I am not sure that what is the real problem which occurred on me. So, do you have any suggestion for me. - When I pickup the source code which wrote by someone. What is the best thing to start consideration how the code work? I know that we should looking for main( ) and typing the code and run. How to convert the code lines to visual image? I have found this porblem especialy when I see very many lines of code.... Thanks in advance from any suggestion.

##### Share on other sites
1. one possibility why you cannot understand someones code could be that this code is bad structured ^^

2. if there are classes look at the header files, the member functions and classes should have names from which you can easily figure out what they do.
Then you could go through every function/member-function and read the code (always having in mind what the function is for)

hth

more doesn't come into my mind at the moment

##### Share on other sites
Use a debugger and single step through the program.

Skizz

##### Share on other sites
My idea is that you must first write your source code and understand it.
every body have spesial habits to write an source code.
Also you can give help from MSDN or something source like it.

##### Share on other sites
thank you for everyone.

More questions, is it important & necessary that we need to understand code mechnical each lines inside each function or.. just only know what the function does? Such as..how to call them? What is parameters which I send to it and what is the value return from function? (In case of I don't wanna modify them)

##### Share on other sites
given enough amount of money under the right circumstances you'll understand the moon shouting out loud she's not the price for a woman's love.

in short, try harder.

##### Share on other sites
Quote:
 Original post by eniCmathank you for everyone.More questions, is it important & necessary that we need to understand code mechnical each lines inside each function or.. just only know what the function does? Such as..how to call them? What is parameters which I send to it and what is the value return from function? (In case of I don't wanna modify them)

The first key point is to understand the purpose of the functions, in order to be able to use them. To do this, you may have to decompose the function in a list of algorithm and study the algorithms. This may require the reading of individual lines for complex algorithm. Debugging can help, because it essentially shows the result of each step of the algorithm.

Remember that reading code is kind of hard - you are not in the mind of the code creator, and you might miss something he considers as being obvious.

Regards,

##### Share on other sites
I don't have much of an advice, just wanted to point out that understanding others code is not the same as writing the code yourself. In most cases, I think it's much easier to make an advanced application by myself instead of trying to understand a fairly basic application that someone else have made.

The difference is in other words that it's much harder to understand something you haven't made yourself, unless you're reading a tutorial where you put down each line step by step where you're following the whole process.

##### Share on other sites
Good code should have comments that make it clear what's going on (so basically, unlike mine :P). If it doesn't, or it's something that really shouldn't be commented, just think about it step by step. Ask yourself "What's going on on this line?" and if you can't understand, take a step back, look at the header files, and classes, functions and data structures to try to understand better.

##### Share on other sites
Well I find it incredibly hard to understand someone's code if I'm not familiar with what he's doing (what the code should be used for), especially if there are no or not clear enough comments.

So I think, basically you should be familiar with the matter befor analysing someone's code. For example, trying to understand some genetic algorithm code is really hard if you don't know what genetic algorithms are.

Understanding someone's code or even your own if a sufficient amount of time has passed since you wrote it is never easy. That's why good variable / class / method names should be used and comments should appear everywhere in your code. I know it's hard to force yourself to comment everything, but from my own experience is it that I have learned that those nice comments help me understand what I did all those months ago. Yet I often do right the opposite (no comments), shame on me.

Additionally I find it usefull to start with some pseudo code comments when I implement some function so I can use them as a guideline, e.g.

//get the object pointer
//move the object if it is movable
//draw it

would end in something like,

//get the object pointer
Object* obj = Pool.getObject();

//move the object if it is movable
if(obj->isMovable())
obj->move();

//draw it
obj->draw();

(OK, very very simple example ;P )

##### Share on other sites
Quote:
 Original post by Lord_Evil(OK, very very simple example ;P )
Be very careful here. The comments in your example are actually dangerous, because they say things that are completely obvious from the code itself. They convey no new information. In general, those sorts of comments just create maintenance problems without improving the clarity or quality of the code at all.

A lot of less experienced programmers -- particularly ones who aren't very good at the language -- fall into this trap. They confuse the purpose of comments, using them to explain what is being doing at that point. You don't need to explain what the code says, the code does that itself. Comments should be used to explain why you're doing whatever it is, or to clarify in situations that are confusing.

Most people don't realize this. Too many comments is frequently worse than not enough comments. I would strip out all of the comments in your example.

##### Share on other sites
When it comes to understanding other people's code, it's mainly a question of experience doing it (it's good that you've started trying).

The key point is to disregard most of the actual code. Study the interfaces and objects, pay attention to how the different modules interact, how information is moved around, etc. Also try to understand how the function call graph will lay out, noting who is calling who and what is being passed.

Look at the actual implementation of things only after you have a solid understanding of the interfaces, modules, and objects.

##### Share on other sites
Quote:
 Original post by eniCmaMore questions, is it important & necessary that we need to understand code mechnical each lines inside each function or.. just only know what the function does? Such as..how to call them? What is parameters which I send to it and what is the value return from function? (In case of I don't wanna modify them)

No, it is not necessary to understand every line. I alway simplify a program down to the minimum it needs to do what I need. This helps learn the code, and removes any extra stuff. Once it's simplified down, learn that line by line.

And, one of the most valuable lessons you can gain from reading someone else's code is the importance of properly writing code. I cannot understand how people, who have been programming for years, can still write unreadable code.

I have code that I wrote 6-7 years ago that I can still maintain, because I took a little extra time to write it. My coding ability has improved greatly since then, so there are many areas I would change today, but I can still understand how it works.

##### Share on other sites
I admit that was a very stupid example.

I'd actually use those comments on a more global scale. This way you can describe a section of complicated code in simple words so you can understand the code more easily.

So, for example describing the steps of an algorithm before implementing it would help you not to forget a critical part and later understand it, when you need to change something.

##### Share on other sites
Quote:
 Original post by BringBackFuturamaGood code should have comments that make it clear what's going on

No - good code shouldn't need comments. Remember that comments can lie, but the code cannot.

##### Share on other sites
Following along the 'how to comment your code' track, I advise the reading of Code Complete (2nd edition). There is a chapter on self-documenting code, and how to comment properly. Promit's post touched on this. I forget the exact numbers McConnell uses, but at max you should only have 1 comment for ever 4-5 lines of code. The function names and variables used should be descriptive. Code should be written in 'blocks', and prefaced with a single comment describing the intent of the block. Recurring 'blocks' should be put into their own well-named function. This is self-documenting code, which eliminates the need for maintenance of comments, among other issues.

##### Share on other sites
I think you can put code into three categories:

3. Perfect code: doesn't need any comments.

If you happen to come across type 2 or 3, with a little practice and knowledge in the language you will be able to understand most parts by simply following the execution line (like game loop order).
If you happen to come across type one, you don't need to worry either, all you need to know is that you don't want to know what the code means ;).

##### Share on other sites
I disagree that no code ever needs comments, if perfectly written. Sometimes (rarely) speed *is* the most important factor, readablility will be sacrificed, and a couple of comments may do just the trick.

I'm taking 'perfect' to mean 'best possible for the situation'.

##### Share on other sites
Could I take myself out of the affair by saying that no code is perfect? ;).

I always comment my source code, and I think the "perfect" parts of it is when the comment matches the variable/function name and basically just rephrases it.
The problem is that it's impossible to produce such clear structured code through the whole project, given the complexity of some parts.
Another thing is that it's not up to you to decide if your code needs comments.

##### Share on other sites
Quote:
 Original post by Lord_EvilI'd actually use those comments on a more global scale. This way you can describe a section of complicated code in simple words so you can understand the code more easily. So, for example describing the steps of an algorithm before implementing it would help you not to forget a critical part and later understand it, when you need to change something.

I'm with you on this one Lord_Evil. I prefer to block my program down in simple english and then fill in the code later on.

// Setup window class// Initialise main window// Setup Direct3D// Main Loop{  // Obtain window message  // Update objects  // Render screen}

I would use something similar to this when writing out my programs but I can see structure before I type a single line of code.

##### Share on other sites
See, those are exactly the sort of comments you should NEVER write. (If you need them as a crutch, fine, but delete them when the code is written.)

##### Share on other sites
What frightens me more than anything is when a coder will begin a project without sufficient planning. No, the whole project doesnt need to be planned as this itself can lead to problems, but in agreeance with Adam Hamilton, a comment-structure can very quickly organize a method, function, or entire program. What I can't entirely fathom is how some of you can say "perfect code" (which doesn't exist due to others definition of perfection) does not contain comments. Mathematical algorithms can be extremely complicated, and reading through their source even when "perfectly" coded can prove a daunting task. Then again, leading a block of code with an explanation which is obvious by the succeeding code is not wrong as it organizes code into structured blocks, which is the foundation of some languages/scripts such as XHTML.

Quote:
 Original post by EzbezI disagree that no code ever needs comments, if perfectly written. Sometimes (rarely) speed *is* the most important factor, readablility will be sacrificed, and a couple of comments may do just the trick.

If you're refering to "speed" as in the speed to write out the program, then I agree. Yet, if you are refering to the speed of the program you must take into account that compilers strip comments, whereby they have no effect on runtime speeds.

To eniCma:
In my humble opinion one of the best ways to understand someone elses code is to firstly block it into major code sections (usually methods and functions) and understand the structure of the program before delving into the individual lines of code. Once the structure is understood do the same with each function starting from square one, and understand what each line is attempting to do. Bare also in mind, for you "perfect coders" that although you understand what is going on in a segment of code, a comment obvious to you could save someone like eniCma a lot of trouble in understanding what is going on.

Then again.. everything falls down to your programming goals: Maintainability, speed, portability... readability...

##### Share on other sites
Thank you for everyone...
So, we let do the real practice now!!

I copy this code from C Programming (K&R) in topic "Pointers to Function"

#include <stdio.h>
#include <string.h>

#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */

void writelines(char *lineptr[], int nlines);

void qsort(void *lineptr[], int left, int right,
int (*comp)(void *, void *));
int numcmp(char *, char *);

/* sort input lines */
main(int argc, char *argv[])
{
int nlines; /* number of input lines read */
int numeric = 0; /* 1 if numeric sort */

if (argc > 1 && strcmp(argv[1], "-n") == 0)
numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void**) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
} else {
printf("input too big to sort\n");
return 1;
}
}

==========================
For my trouble, when I first saw any code such as like this code (complex & a lot of nest if/loop), I felling very confuse.. 1st question in mind..how I can start to figure out each line or purpose of code?

NOW! Follow all of your above comment.... I begin to finding "comment" & "structure porgam" ... and "see the Fucntions"...

This is my summary...
- This code demonstrate "Pointer to function" concept
- There are four function in this code.. (readlines, writelines, qsort and numcmp)
- Then the code read input line & going into main( )... then if if if
- It's seem that from line...

if (argc > 1 && strcmp(argv[1], "-n") == 0)
numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void**) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
} else {
printf("input too big to sort\n");
return 1;
}

I don't know the mechanical of each line (because it doesn't have comment, so this is bad practice programming?)...

However, I can figure out what is the command on each line but... don't know "why we do that???..." Not sure... It's seem that I am poor of generic algorithm knowledge now??? right?

This is mt trouble that I said ... :(

##### Share on other sites
OK let's try it.

//uses string and io routines
#include <stdio.h>
#include <string.h>

//seems to be used for sorting text lines
#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */

//reads a number lines from the pointer array

//writes a number of lines to the pointer array
void writelines(char *lineptr[], int nlines);

//Quicksort on the line array?
void qsort(void *lineptr[], int left, int right,
int (*comp)(void *, void *));
//Function for comparing strings numerically?
int numcmp(char *, char *);

/* sort input lines */
main(int argc, char *argv[])
{
int nlines; /* number of input lines read */
int numeric = 0; /* 1 if numeric sort */

//read the comandline arguments and check for -n option?
if (argc > 1 && strcmp(argv[1], "-n") == 0)
numeric = 1;

if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
//if lines could be read, sort them. Use compare function based on "numeric" variable
qsort((void**) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
//write the sorted lines somewhere
writelines(lineptr, nlines);
return 0;
} else {
printf("input too big to sort\n");
return 1;
}
}

OK, that code seems to read some text lines, sort them with Quicksort based on text or numerical comparinsons (depends on commandline option -n), an writes the sorted text somewhere.

So now the questions:

Where do the lines come from?
Where are they written to?

That should be answered by the implementations of the functions "readlines" and "writelines".

[Edited by - Lord_Evil on September 22, 2006 5:03:09 AM]

##### Share on other sites
I agree that perfect code would require no comments whatsoever. The stated reasons for objecting to this seem to be implying that commenting code is the only way to express the author(s) intention. This isn't the case, though, as the language itself lets you express intent. Clean structure and good names can convey oodles of information about what's going on, and in appropriately bite-sized pieces.

In almost all of my code, almost all of the comments are function-header comments, and those are mostly there to provide easy-on-the-eyes separators between functions. Most of the other comments are to explain why an odd construct or approach was taken, or to warn the user about some potentially unexpected or dangerous behavior.