Return from void function

This is a more correct way to return from a function:

void function() { // blah some code } 

OR

 void function() { // blah some code return; } 



Justification for the second way:

  • It more clearly expresses the intentions of the developers.
  • This helps to detect the end of the function at compile time:

Suppose you have a scenario like this: you have a bunch of functions, and you have to enter some code at the end of these functions. But for some reason you do not want / cannot change such a huge number of functions. What can you do about this? Return and macro , for example:

 #include<stdio.h> #define MAX_LINES 1000 #define XCAT(a,b) a##b #define CAT(a,b) XCAT(a,b) #define return returns[__LINE__] = 1;\ if (returns[__LINE__])\ {printf("End of function on %d line.\n",__LINE__);}\ int CAT(tmp,__LINE__); \ if ((CAT(tmp,__LINE__)=returns[__LINE__], returns[__LINE__] = 0, CAT(tmp,__LINE__)))\ return static int returns[MAX_LINES]; void function1(void) { return; } void function2(void) { return; } int main() { function1(); function2(); return 0; } 
+45
c function void
Jan 25 '12 at 13:11
source share
5 answers

Rather, so make a choice. Empty return; provided to return to the void function from a place other than the end. There is no other reason why I believe.

+44
Jan 25 2018-12-12T00:
source share

The only reason for returning to the void function will be the exit due to some conditional statement ...

 void foo(int y) { if(y == 0) return; // do stuff with y } 

As the saying goes, when the code ends, it ends. There is no need for an explicit return at the end.

+45
Jan 25 2018-12-12T00:
source share

The first way is more correct, what intention can be expressed? If the code ends, it ends. This, in my opinion, is pretty clear.

I do not understand what may be confusing and need clarification. If there is no loop construct, then what could happen otherwise than the function stops executing?

I would be annoyed by such a meaningless return addition at the end of the void function, since it obviously has no purpose and just makes me feel like the original programmer said: "I was confused about this, and now you can too! Which is not very nice.

+20
Jan 25 '12 at 13:12
source share

Old question, but I will answer anyway. The answer to this question is that bare return is redundant and should be ignored.

In addition, the proposed value is false for the following reason:

 if (ret<0) return; 

Rethinking the reserved word C as a macro is a bad idea at first glance, but this particular sentence is simply inappropriate, both the argument and the code.

+1
03 Sep '15 at 17:11
source share

void is a unary operator. It can be used in self-dependent functions. Just like with +, -, ~ ,! Operators

 void function(){ console.log("test"); }(); !function(){ console.log("test"); }(); 
-3
Dec 08 '13 at 19:35
source share



All Articles