سؤال

Does someone know the internal differences between :

void RecFoo1(int bar){
  if (bar == 0)
    return ;
  RecFoo1(bar - 1);
}

and

void RecFoo2(int bar){
  if (bar == 0)
    return ;
  return RecFoo2(bar - 1);
}

I am convinced that it is always better to put the return keyword. If the recursive function is not a void function, one will get a warning from -Wreturn-type. But are these two piece of code compiled/executed the same way or not ? What are the internal differences for the machine ?

My example of function is stupid but it constitute a kind of minimal example...

هل كانت مفيدة؟

المحلول

The C standard is quite clear on this, your RecFoo2 example is not a valid C program:

6.3.2.2 void

The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, ...

and

6.8.6.4 The return statement

Constraints

A return statement with an expression shall not appear in a function whose return type is void.

نصائح أخرى

In a void function, return is simply a control-flow operation - exit the current function. You could add one in the last line of the function:

void RecFoo1(int bar){
  if (bar == 0)
    return ;
  RecFoo(bar - 1);
  return; // Unnecessary!
}

But it's completely redundant.

Your second query won't compile - you can't return a value in a void function.

There is no real difference. Actually I expected to get no difference at all, but look at this.

Compare of generated assembly code without optimizations (got it by passing -save-temps option to gcc):

diff --git a/without-expr.s b/with-expr.s
index a7577f5..e346d6f 100644
--- a/without-expr.s
+++ b/with-expr.s
@@ -18,6 +18,7 @@ L2:
        decl    %eax
        movl    %eax, (%esp)
        call    _RecFoo2
+       nop
        jmp     L1
 L4:
        nop

With optimizations generated code is exactly the same (I tried -O2).

So without optimizations compiler generates an extra nop for return with an expression, but it's not something you should really care about.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top