[prog] C programming - capturing information sent to stdout

Mary mary-linuxchix at puzzling.org
Thu Jul 14 10:47:56 EST 2005


On Thu, Jul 14, 2005, Conor Daly wrote:
> assert does a test.  If the test fails, the program halts with a
> hopefully useful error message.  It should be used liberally for
> debugging anywhere in your code where you expect a variable to be a
> certain value.
> 
> That's not very well explained at all...

One way to think of it is that you should use it to enforce pre- and
post-conditions on your functions, particularly when debugging.

For example, if method getDatabaseInfo expects that all the data has
already been converted to lowercase before it is called, you can put an
assert in that checks that. That way, if during development of the code,
another programmer doesn't take note of the pre-condition which is
presumably described in comments, they will get a nice quick crash with
"argument databaseQuery was not in lowercase" rather than have to work
it all out backwards from getDatabaseInfo returning a funny result.

Likewise, if you have a bug and either suspect that it is because
getDatabaseInfo returned a funny result, or want to confirm that it
*wasn't* getDatabaseInfo returning a funny result, you can assert right
after it returns to check whatever correctness it is that you're worried
about.

Like all error checking, there's a pragmatic limit to how much you
should do this. This would usually be an absurd example:

int x = 6;
assert (x == 6);
y = x + 2;
assert (x == 6);
assert (y == 8);

But even that might be useful if this is running in a thread and you
want to debug a data corruption problem due to interaction with a second
thread. And you can use asserts like debugging print statements: put
them in to solve a bug, take them (or some of them) out when it's fixed.

Note that assert, because it makes your program crash, is not designed
to handle *expected* error (error that you anticipate happening in the
normal course of your programming running) like badly formed input from
users (imagine if Firefox crashed every time you put in a URL that
didn't work!) or the network going down, or the database returning no
results.

I would use it mostly for debugging and for enforcing pre-conditions on
code that I expect other people to use (like a library I write or a
group project) so that people find out nice and quickly when they use a
method in a way I don't expect. Like much programming, this may happen
backwards: you only realise a pre-condition exists when someone tries
something you never expected ("oh! you tried it with UPPERCASE? I didn't
expect that!") and you then put the assert in to make sure noone else
makes the same mistake.

-Mary


More information about the Programming mailing list