4

I wish to use || statements to stop execution flow once any of my functions returns a non-zero error code. However, if I use "bare" logical statements, as in

void function myFun(void)
{
    struct myStruct *test = malloc(sizeof(struct myStruct));

    if (!test)
        return ;

    (subFun1(&test) ||
     subFun2(&test) ||
     subFun3(&test) ||
     subFun4(&test));

    free(test);
}

gcc complains

error: value computed is not used [-Werror=unused-value] 

I could also write something like that,

void function myFun(void)
{
    struct myStruct *test = malloc(sizeof(struct myStruct));

    if (!test)
        return ;

    if (subFun1(&test) ||
        subFun2(&test) ||
        subFun3(&test) ||
        subFun4(&test))
    ;

    free(test);
}

but it looks super-awkward.

What is the best way to handle this?

GingerBadger
  • 312
  • 3
  • 12
  • 2
    `if (subFun1(&test) == 0 && subFun2(&test) == 0 && subFun3(&test) == 0) subFun4(&test);` (or you can use `!subFunN(&test)` for each term but it isn't as clear IMO). – Jonathan Leffler May 23 '20 at 04:58
  • @dxiv But do still get the control flow I want in the first case (i.e. if any function returns a non-zero value, the following functions don't get called)? Is the second way better overall? And is there a more elegant way? – GingerBadger May 23 '20 at 04:58
  • 5
    @GingerBadger Sorry, I misunderstood what you meant by "flow" at first, so safely ignore my previous now-deleted comment. You could rewrite the first version as `(void)(subFun1(&test) || ...);` to silence the warning, though in the end it's a matter of preference. – dxiv May 23 '20 at 05:06
  • 4
    The standard way to suppress a warning about an unused value is to cast it to `void`. This doesn't generate any code, but it discards the value in a way that doesn't cause a warning. – Tom Karzes May 23 '20 at 05:49
  • wouldn't a cast cause it to always return false? @dxiv – Imeguras Nov 08 '21 at 10:35
  • @Imeguras Not sure what you mean. Such a cast does not change the return value, and the calling code does not use that value anyway. – dxiv Nov 08 '21 at 16:28
  • @dxiv oh wait its the overall result not the individual functions result right? – Imeguras Nov 08 '21 at 18:15
  • @Imeguras Lookup *short-circuit evaluation*. The intent here is that if one of the calls returns true, the other calls are skipped altogether. – dxiv Nov 08 '21 at 18:20
  • oh i thought the opposite i thought that if one were to return true since its a or it would skip @dxiv – Imeguras Nov 08 '21 at 18:21
  • @Imeguras Right, I edited my previous comment to fix that. – dxiv Nov 08 '21 at 18:22

0 Answers0