patterncMinor
Implementing N-ary trees in C
Viewed 0 times
implementingarytrees
Problem
Looking at my code, I feel like it is not instantly clear for someone who did not write it. I feel like readability will be important for me in the future, if I'm ever to write code on an enterprise, or open source project. Do you have any advice as to how I can make this and future C more readable?
datatypes.h
#include "datatypes.h"
#include
//Changes the node's child (if it doesn't exist) to newChild
//or appends newChild to the end of the node's child's sibling list
void addChild ( treeNode *root, treeNode *newChild ) {
treeNode *temp;
if ( root->child == NULL ) {
root->child = newChild;
} else {
temp = root->child;
while ( temp->sibling != NULL ) {
temp = temp->sibling;
}
temp->sibling = newChild;
}
}
//Returns a new treeNode with default data values or {0,NULL,NULL}
treeNode newNode () {
treeNode node = {0, NULL, NULL};
return node;
}datatypes.h
typedef struct treeNode {
int n;
struct treeNode *child;
struct treeNode *sibling;
} treeNode;
treeNode newNode (); //Returns a treenode with default {0,NULL,NULL}
void addChild ( treeNode *t, treeNode *c ); //Adds child to the given treeNodeSolution
Comment, Comment, Comment. If you want any other person on this blue planet to know whats going on in your code in the easiest way possible, comment your code.
Your code doesn't have to be pretty or legible for that matter, but a few comments go along way.
Also, whitespace for your
// This is what the code does in the next line.
/* I'm going to write a block of text to tell you the purpose of what this function
is trying to accomplish */Your code doesn't have to be pretty or legible for that matter, but a few comments go along way.
Also, whitespace for your
if and while statements are appealing to the eye and allow the reader to break apart your conditional statements. Trying to cram as much as you can on one line causes headaches when trying to interpret them.Code Snippets
// This is what the code does in the next line.
/* I'm going to write a block of text to tell you the purpose of what this function
is trying to accomplish */Context
StackExchange Code Review Q#107708, answer score: 4
Revisions (0)
No revisions yet.