Re: typedefs and structs

From: Kyle Moffett
Date: Tue Nov 08 2005 - 18:57:54 EST


On Nov 8, 2005, at 18:23:27, linas wrote:
Off-topic: There's actually a neat little trick in C++ that can help avoid accidentally passing null pointers. One can declare function declarations as:

int func (sturct blah &v) {
v.a ++;
return v.b;
}

The ampersand says "pass argument by reference (so as to get arg passing efficiency) but force coder to write code as if they were passing by value" As a result, it gets difficult to pass null pointers (for reasons similar to the difficulty of passing null pointers in Java (and yes, I loathe Java, sorry to subject you to that)) Anyway, that's a C++ trick only; I wish it was in C so I could experiment more and find out if I like it or hate it.

That technique tends to cause more problems than it solves. If I write the following code:

struct foo the_leftmost_foo = get_leftmost_foo();
do_some_stuff(the_leftmost_foo);

How do I know what it is going to do? Will it modify the_leftmost_foo, or is it a pass-by-value as it appears? This is just as bad as defining a macro some_macro(foo,bar) that does (foo = bar), it's _really_ hard to tell what it does, especially when you aren't all that familiar with the code. A much better solution is this:

void do_some_stuff(struct foo *the_foo) __attribute__((__nonnull__(1)));

do_some_stuff(&the_leftmost_foo);

That ensures that the first argument cannot be explicitly passed as null, while still being quite obvious to the programmer what it's doing.

Cheers,
Kyle Moffett

--
They _will_ find opposing experts to say it isn't, if you push hard enough the wrong way. Idiots with a PhD aren't hard to buy.
-- Rob Landley



-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/