Short Circuit Error Handling in C

I was wondering if there is a better way to handle the situation in C where you want to exit the function as soon as you encounter an error in a series of expressions. (in this case, it is a function that returns a NULL error on error)

eg. in some C code, where they tried to handle errors in short circuits by combining a number of operators with AND (& &).

return doSomething() && 
     doSomething2() && 
     doSomething3() && ... ;

This annoys me, as we click so much on one line in one of the statements. But I guess the alternative

if (!(value = doSomething()))
    return NULL;
if (!(value = doSomething2()))
    return NULL;
etc
return value;

But what about evaluating errors in the short circuits that I saw in the perl and bash scripts.

int die(int retvalue) {
    exit(retvalue);
}
.....
(value = doSomething()) || die(1);
(value = doSomething2()) || die(2);
(value = doSomething3()) || die(3);
return value;

, RHS , . - ?

edit: , . , , .

+3
6

GOTO C .

C "" , , .

, ( - C, , )

int foo()
{
    /* Do Stuff */
    if(!DoSomething())
        GOTO Failure;

    if(!DoSomething2())
        GOTO Failure;

    if(!DoSomething3())
        GOTO Failure;

    /* return success */
    return true; 

    Failure:
    /* release allocated resources */
    /* print to log if necessary */
    return false;
}

GOTO . . - , , . .

, Exit (x) , . (DS() & DS2() & DS3()) .

- , , . , , -

int result1 = 0;
int result2 = 0;
int result3 = 0;

result1 = DoSomething();

if(result1)
    result2 = DoSomething2();

if(result2)
    result3 = DoSomething3();

return result1 && result2 && result3;

.

+5

, , :

return doSomething()
    && doSomething2()
    && doSomething3()
    && ... ;

:

if (!(value = doSomething()))  return NULL;
if (!(value = doSomething2())) return NULL;
: : : : :
return value;

( , ), ( ).

+4

- ?

int result;

result = doSomething();

result = result && doSomething2();

result = result && doSomething3();

return result;

, ..

+1

. C ; . , .

, , .

0

C, , , if, . , . , , , .

, .

:

int copy_string(char *source, char *target, size_t max)
{
    if (source == NULL)
        return -1;
    if (target == NULL)
        return -1;
    source_len = strlen(source);
    if (source_len + 1 > max)   // +1 for NUL
        return -1;
    memcpy(target, source, source_len + 1);
    return 0;
}

( Unix -1 , .)

0

:

int Function (void)
{
    int Result = DoSomething();

    if (Result) Result = DoSomething2();
    if (Result) Result = DoSomething3();
    if (Result) Result = DoSeomthing4();

    return Result;
}

, . , . , , , . if (!Result), .

0

Source: https://habr.com/ru/post/1706324/


All Articles