I tend to comment code when it could be unclear why something is done where (or how) it's done. Examples (from real code of mine, unedited) follow. After each sample is additional comments about it.
Code: Select all
// sin, except basic period is [-0.5, 0.5]
double Msin (double x) const {
x -= rint(x);
x *= 2 * M_PI;
// this is basic 7th order Maclaurin for sin(x)
// and it's quite accurate at [-Pi/2, Pi/2]
// and more or less decent at about [-Pi, Pi]
//
double x2 = x*x;
return x*(1+x2*(-1+x2*(1-x2*(1.0/42))*(1.0/20))*(1.0/6));
}
Ok, first of all, the first comment is important, because otherwise you'd get the period is what real sine has. If somebody thinks they could figure out where the function came from without the second comment, then they should be doing maths and not CS.
Code: Select all
// some bogus value, any bogus value will do.. just bogus enough ;)
height.last_x = height.last_y
= light.last_x = light.last_y
= blend.last_x = blend.last_y = 0xDEADBEEF;
Seriously, that comment probably explains something. Now that I think of it, it probably SHOULD tell WHAT kind of value is "bogus enough". Then again, I think that if someone wanted to change that value, that someone would understand the relevant piece of code well enough to know what to do.
Code: Select all
// If XMODIFIERS is not set, we probably want to
// use X Servers internal translation instead of
// "none" which would default.
if(getenv("XMODIFIERS"))
XSetLocaleModifiers(""); // failure is non-fatal..
else XSetLocaleModifiers("@im=");
The first comment tells why we actually bother, and saves an API check by telling what we do. The second small comment saves another API check by telling that we ignore return values because it doesn't really matter.
Code: Select all
// These two friends manipulate the "parent" attribute.
// They would be Container's members if that wouldn't cause
// unfortunate cyclic definitions.
friend void Container_add(Container *, Component *);
friend void Container_remove(Container *, Component *);
Another comment that tells something non-obvious. In this case we tell the reader not to bother trying to "fix" it.
Code: Select all
// seems to be needed on x86, probably endian dependant..
png_set_bgr(png);
This comment tells the reader that the line has a purpose, even if that purpose might not have been 100% clear when the line was added. It also kinda warns a future debugger that there might be something dubious here.
Code: Select all
return 0; /* should not be reached !! */
Classic. Tells everyone that the return there is just to get rid of a compiler warning.
Ok, so I hope this set of examples was wide enough to give you people an idea of what I comment and how.