[mercury-users] Premature exit from pragma c_code pred/func?
Fergus Henderson
fjh at cs.mu.OZ.AU
Wed Dec 1 13:58:20 AEDT 1999
On 30-Nov-1999, Warwick Harvey <wharvey at cs.monash.edu.au> wrote:
> Is it possible (in a det/semidet context) to exit prematurely from a `pragma
> c_code' definition of a predicate/function? That is, to do something
> analogous to inserting a `return' in the middle of a normal C function?
>
> I'm trying to convert a C function into a `pragma c_code' implementation of
> a Mercury function. The basic structure of the body of the function is:
>
> ...1...
> while (...2...) {
> ...3...
> if (...4...) {
> ...5...
> return ...6...
> }
> ...7...
> }
> ...8...
> return ...9...
[I added the numbers to the code quoted above.]
You could rewrite it as
{
RetType ret_val;
...1...
for(;;) {
if (!(...2...)) {
...8...
ret_val = ...9...
break;
}
...3...
if (...4..) {
...5...
ret_val = ...6...
break;
}
...7...
}
...
}
> Of course I can rewrite the code to only have one exit point, but it would
> be convenient if I didn't have to do that, and the resulting code would
> probably be more efficient (modulo my limited understanding of how this
> stuff works).
The above rewrite is not quite as nice as the original code, it's true,
but it will be just as efficient.
If you want a more elegant solution, I suggest defining the code in
a separate C function, declared inline:
:- pragma c_header_code("
#ifdef __GNUC__
#define INLINE __inline__
#elif __STDC_VERSION__ >= 199901 /* Jan 1999 */
#define INLINE inline
#else
#define INLINE
#endif
INLINE RetType foo(...) {
...1...
while (...2...) {
...3...
if (...4...) {
...5...
return ...6...
}
...7...
}
...8...
return ...9...
}
").
Then make your `pragma c_code' procedure just call this function.
For maximum efficiency you might have to compile with MGNUCFLAGS=-O3,
but I _think_ gcc will inline it even at -O2 (which is what mgnuc uses
by default) if you explicitly declare it inline.
Cheers,
Fergus.
--
Fergus Henderson <fjh at cs.mu.oz.au> | "I have always known that the pursuit
WWW: <http://www.cs.mu.oz.au/~fjh> | of excellence is a lethal habit"
PGP: finger fjh at 128.250.37.3 | -- the last words of T. S. Garp.
--------------------------------------------------------------------------
mercury-users mailing list
post: mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe: Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------
More information about the users
mailing list