Re: maths for programming C++

Logan Shaw said:


I'm afraid I have to agree with Mr. Heathfield on that. Buggy-
but-readable programs can easily be fixed.

Not necessarily. If fixing them makes them even slightly less
readable, then it's not allowed under the rules, because readability
is valued more than correctness.

"A foolish consistency is the hobgoblin of small minds" - Ralph Waldo

But let's see whether you can give a concrete example, and see where it
takes us.

Let me give a concrete example.

Ah, you've been reading my mind again. Let's hope my mind is both readable
and correct!

Here's a program:

#include <stdio.h>

int main ()
size_t x = 8;

printf ("%d\n", x);

The readability of your program could certainly be improved by proper use of
Usenet-proof indentation.

Since it's a C++ program, I'll buy the empty (), I suppose, although I don't
like it.

But the absence of a return statement from a function defined to return a
value strikes me as taking undue advantage of the language definition.

And, since it's a C++ program, shouldn't you be using C++ idioms, such as
<cstdio>? In fact, shouldn't you be using <iostream> instead, together with
std::cout and all that?

Anyway, the bug in your program stands out a mile, as you no doubt intended.

Now, here's a correct program (or at least one with fewer bugs):

#include <stdio.h>
#include <stdlib.h>

Why include <stdlib.h>? You don't need it.

int main (int argc, char *argv[])

Why the arg stuff? You don't need it.

size_t x = 8;

printf ("%lu\n", (unsigned long) x);

Ah, that's better. Well done - you fixed the bug, and the program reads more
cleanly as a result. At least, it does to me. Since I know that x type
size_t, its value without a cast like a sentence that its verbs. Such
sentences do not read well.

return 0;

Which one is more readable? To me, it's the first.

Let's put up a third version (and remember this is C++, not C, so I'll omit
void to protect the poor innocent C++ folks against the unmitigated evils
of explicitly empty parameter lists):

#include <stdio.h>

int main()
size_t x = 8;

printf("%lu\n", (unsigned long)x);

return 0;

There's less clutter [in the first program], and it's readily
apparent what the programmer intended.

Your second version, and my version, include the cast. Casts are rarely
needed, but this is one case where the cast /is/ needed, and necessary
stuff can hardly be called clutter.

The return 0; might be considered clutter, but I add it because it adds
readability - it does not leave the reader wondering about what value will
be returned.

So, under the rules of readability over correctness, the second
program isn't allowed.

And under the rules of correctness, the first version isn't allowed either.
So let's go for the third version instead.

Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
email: rjh at above domain (but drop the www, obviously)