CS 225 Programming Notes
These are some things I noticed in programs that I want to comment on so
you can tell what I am looking for in grading programs. Some of these are
style issues that are important, but there is no one right way to do them.
I'll try to be specific in the notes.
-
Spacing and indentation
Spread the program out of the page. Leave spaces around parts of
statements. Leave space between sections of code. Think of paragraphs.
Several lines of code that work together to solve part of the problem are
a paragraph and should be set off from the rest of the code.
-
Comments
Put long comments above the line, putting them after hides the code when
they wrap. Also, tell me what the statement is for, not what it does.
x++; // increment x
is not helpful
x++; // increment the vowel counter
is helpful, especially since x is not a good name for this. vowel_counter
would have been better.
-
Constants
I make my constants all capital letters so they stand out in the code.
That makes them more noticeable.
-
Globals
Use globals sparingly, they make fixing a program harder since they can
be changed anywhere. I make the first letter in a globals name a capital
letter to make them stand out.
-
Initialization
It is very important to initialize variables before you use them. But you
don't need to set all the elements in an array to zero before you start
putting string characters in it. Only the element after the last character
needs to be zero. When initializing string constants, like
char * vowels = "aeiou";
you don't need to put the '\0' at the end. The compiler will do this for
you.
-
Allocating memory
If you declare a character pointer like this
char *cptr;
And then you do something like
char *vowels="aeiou";
char *src=vowels;
while(*cptr++ = *src++) ;
this will only work by accident. There is no memory assigned to cptr and
you are copying the characters from vowels to some unknown memory location.
If the location is part of the operating system, you could crash the computer.
You cam make a safe chunk of memory by doing
cptr = new [strlen(vowels) + 1];
-
Pointer arithmetic
If you have a pointer to the beginning of an array and one to the end,
it isn't safe to calculate the length by subtracting the first pointer
from the second. Some systems use memory in the other direction and this
will give you a negative number.
-
0 is false
When using strings, you can check if you are at the end by just checking
the value.
if(string[i])
is fine, you don't need to do
if(string[i] != '\0')
Doing this will confuse experienced C++ programmers.