Return Status C or C ++

What are the best methods for writing C or C ++ functions that return an int that represents a status code?

In particular, I want to know about the client, but welcome other tips.

For example, can I write something like this:

int foo() {
  return 0;  // because everything was cool
}

And then use it like this:

if (foo()) {
  // what to do if false, e.g. non-zero, e.g. not OK
} else {
  // what to do if true, e.g. zero, e.g. OK
}

This should work, because best practices usually determine that a status code 0means that everything is in order, and also 0means falsein a logical expression.

However, this will not be good, right:

if (!foo()) {
  // what to do if true
} else {
  // what to do if false
}
+5
source share
7 answers

We use this in C, where I work:

int err = foo();
if (err) {
    // armageddon
}

, , ( gcc ).

++ , , .

: 0 - . , unix.

+9

, enum #define, .

:

enum
{
   kSuccess = 0,
   kFailure = -1,
}

function foo()
{
    return kSuccess;
}

if (kSuccess == foo())
{
    // Handle successful call to foo
}
else
{
    // Handle failed call to foo
}

, , , , - .

+5
if (foo()) {
  // what to do if false
} else {
  // what to do if true
}

. , , :

if(foo1()) {
    if(foo2()) {
        if(foo3()) {
            // the rest of your code
        } else {
            // handle error
        }
    } else {
        // handle error
    }
} else {
    // handle error
}

, :

if(!foo1()) {
    // handle error
    return;
}

if(!foo2()) {
    // handle error
    return;
}

if(!foo3()) {
    // handle error
    return;
}

. . . . ​​ goto

if(!foo1()) 
    goto error1;

if(!foo2())
    goto error2;

if(!foo3())
    goto error3;

return;

error1:
    // handle error
    return;
error2:
    // handle error
    return;
error3:
    // handle error
    return;

.

, goto . . goto C Eli Bendersky .

+2

. 0 ( !), 0 ( enum , OK ).

, . ++ - .

+1

, , .

+1

, :

enum fooret { GOOD, BAD, UGLY, WORSE };

fooret foo();  // defined elsewhere

switch(foo())
{
case BAD:
case UGLY:
   // maybe a recoverable failure(s)...
   // take appropriate actions
   break;
case WORSE:
   // maybe non-recoverable
   break;
case GOOD:
   // successful, take appropriate actions
   break;
}
0
int foo() {
   try{
    ...
   return 1
   }
   catch
   {
   return 0;  // because everything was cool
   }
}

I would start by packing everything into a try / catch block. In addition, instead of using and int, it can do more scenes to return a boolean. This is a little intuitive when testing in an if statement.

-2
source

All Articles