#C Functions which can return some value or an error code

1 messages · Page 1 of 1 (latest)

tired saffron
#

Hello friends, I'm looking to hone in my coding style for pure C functions which can fail or return a value. I think traditionally a lot of libaries return error codes and treat one of the parameters as an output variable via a pointer. Although, I saw zig has an error union type. Basically automatically create a structure which appends an error code to the struct, I was considering using macros to emulate this functionality, what are your thoughts?

// Traditional
error make_context( context_struct * out_context, const input_params* const in_params );
int main() {
    error err = make_context(&ctx, &in_params);
    if(err != success) return err;
    ctx.do_something();
}
// Error Union
MAKE_ERROR_OR_STRUCT(context_struct)
context_struct_or_error make_context( const input_params* const in_params );
int main() {
    context_struct_or_error ctx = make_context(&in_params);
    if(ctx.err != success) return err;
    ctx.value.do_something();
}
lyric swift
#

what problem do you currently encounter with the standard pattern, and that the zig approach would solve?

tired saffron
#

I guess a minor problem it fixes is needing to input validate an extra parameter, part of me also feels like it could potentially look cleaner?

lyric swift
#

as far as I know, union members in C cannot be safely accessed without knowing which member is active (likely a problem zig doesn't have, because the type system is different)

#

(so I guess you'll need to return a flag anyway, maybe a { flag, stuff } structure)

tired saffron
#

Yeah, I was thinking of generating a {flag, stuff} approach

#

However, I guess one advantage of the traditional approach is that functions will have the same layout if it can fail but doesn't return some other value

lyric swift
#

I don't know I don't have a strong opinion here

#

personnally I tend to appreciate error-function that return a pointer, because it allows for NULL while keeping the signature clean

#

(but I guess it depends what kind of errors we're talking about?)

tired saffron
#

Yeah, I definitely get that, for me I don't want the libraries to make an allocations

#

So I can't do returning pointers

#

I guess I might as well stick to the traditional method, as you're right; I can't think of any particularly fantastic examples

lyric swift
#

(or else passed as a pointer in argument, but you didn't like this approach)

tired saffron
#

I was using the pointer argument approach, but was considering trying a different approach

#

but it seems most reliable

lyric swift
#

maybe others will have better insights to provide

tired saffron
#

Thanks for your insights tho, talking things through helps haha

boreal obsidian
#

just do the traditional way