> It's a common mistake to add a return statement to the middle of a function like this, shorting out the cleanup code; flow.js can catch errors like that at compile time.
It's a dumb mistake to use goto like that in C++, the cleanup code should go in a destructor. Removing that sort of fail from the mozilla code would make flow.js unnecessary.
Posted Jan 25, 2010 14:20 UTC (Mon) by clugstj (subscriber, #4020)
[Link]
That example was referring to kernel code, which is in "C" and won't soon be translated to "C++".
LCA: Static analysis with GCC plugins
Posted Jan 25, 2010 14:38 UTC (Mon) by jwakely (subscriber, #60262)
[Link]
Oops, my mistake. I misread it as saying flow.js was used for checking that idiom in Mozilla code, and could also be used for other code such as the kernel. The idiom makes perfect sense in C.
LCA: Static analysis with GCC plugins
Posted Jan 25, 2010 14:45 UTC (Mon) by jwakely (subscriber, #60262)
[Link]
Posted Feb 10, 2010 3:44 UTC (Wed) by bzbarsky (guest, #63464)
[Link]
Yeah, those are all code that used to be C code, then was converted to compiling as C++ with minimal changes made in the process. Now it's starting to use C++ idioms as needed to make the code more understandable, etc.
multiple returns in C
Posted Jan 28, 2010 3:46 UTC (Thu) by thedevil (subscriber, #32913)
[Link]
Actually there's a better way to do this even in C:
static int foobar_return_handler(void* some_pointer, int destruct, int result)
{
if (some_pointer)
free(some_pointer);
if (destruct)
do_destruct();
return result;
}
int foobar()
{
void* some_pointer = malloc(sizeof(some_type));
if (!some_pointer)
return foobar_return_handler(0, 1, -1);
int foo_result = foo(some_pointer);
if (foo_result < 0)
return foobar_return_handler(some_pointer, 1, foo_result);
int bar_result = bar(some_pointer, foo_result);
if (bar_result < 0)
return foobar_return_handler(some_pointer, 1, bar_result);
return foobar_return_handler(some_pointer, 0, bar_result);
}
multiple returns in C
Posted Jan 28, 2010 10:04 UTC (Thu) by dgm (subscriber, #49227)
[Link]
Another idiom I often use is separating resource allocation from actual computation:
int foobar1 (some_type * some_pointer)
{
int result = foo (some_pointer);
if (result < 0)
result = bar (some_pointer, result);
return result;
}
int foobar()
{
int result = -1;
void * some_pointer = malloc (sizeof (some_type));
if (some_pointer) {
result = foobar1 (some_pointer);
free (some_pointer);
}
return result;
}