Which is more correct way to return from function:
void function() { // blah some code }
OR
void function() { // blah some code return; }
Rationale for second way:
Suppose you have such scenario- you have bunch of functions and you must inject some code at the end of those functions. But for some reasons you don't want / or can't modify such huge amount of functions. What can you do about that ? Return
& macro
comes into play, 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; }
A void function can return A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.
Use return; instead of return(0); to exit a void function.
In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.
Neither is more correct, so take your pick. The empty return;
statement is provided to allow a return in a void
function from somewhere other than the end. No other reason I believe.
The only reason to have a return in a void function would be to exit early due to some conditional statement:
void foo(int y) { if(y == 0) return; // do stuff with y }
As unwind said: when the code ends, it ends. No need for an explicit return at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With