Do not return anything from non-void in C

what is considered best practice in the following snippet:

int foo(struct data *bar, struct info bla) {
    if (!bar) {
        bla->status = 0;
        return;
    }
    ...
}

in fact, it works great. but I feel uncomfortable when gccgiving me a warning.


here is the actual code:

static int pop(struct stack **stack, struct info *info) {
        int ret;
        struct stack *tmp;

        if (!*stack) {
                info->error = 0;
                return;
        }

        ret = (*stack)->data;
        tmp = *stack;
        *stack = (*stack)->next;
        free(tmp);

        return ret;
}
+3
source share
8 answers

The best practice is not to write such code. If you cannot return an integer of a specific type at this point, you need to reconfigure your code. Note that a function with a name will return some value to the calling code - you just don't know what that value will be.

, :

int f( int * p ) {
   if ( bad ) {
       return 0;   // fail indicator
   }
   else {
      * p = 42;    // integer return value
      return 1;    // success indicator
   }
}

: . - undefined , , , ( 0) .

+11

undefined, ! void.

+4

, , 0. , , .

+1

return 0; return -1;, , .

0

, , , , .

0
int main(void)
{
    printf("hello world\n");
}

10. bash Mac OS X . , int - , , . , , . - , void, , . , , void.

0

, " " , enum, ( "STATUS_OK", "STATUS_FAIL", "STATUS_NO_RESULT" ..).

, (.. "STATUS_NO_RESULT" ).

0

info->error, , , , , . return -1, return 0, return MAGIC_NUMBER......

" ": , . int , , , . info int data, func.

, -

if ( pop(stack, info) == SUCCESS ) {
  // ...
  printf("%d\n", info->data);
} else { /* failure */
  // info->data holds no data, but info->error could be an error code, e.g.
  fprintf(stderr, "can't pop: %s\n", error_msg[info->error]);
}

:

data = pop(stack, info);
if (info->error != ERROR) {
  // data is valid
} else {
  // data is garbage and we have to say an error occurred.
}

By the way, you do not set info->errorto something else to 0, so your code is potentially bugged; eg.

  info->error = 0;
  data = pop(stack, info);

always caused an error, even if the stack is really in order, and therefore the data is valid.

0
source

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


All Articles