Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning from a void function [closed]

Tags:

c

function

void

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:

  1. It expresses developer intentions more clearly.
  2. It helps detecting function end at pre-compile time:

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; } 
like image 965
Agnius Vasiliauskas Avatar asked Jan 25 '12 13:01

Agnius Vasiliauskas


People also ask

Can you return from a void function?

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.

How do you get out of a void function?

Use return; instead of return(0); to exit a void function.

What happens when we use return in 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.


2 Answers

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.

like image 164
William Morris Avatar answered Sep 21 '22 07:09

William Morris


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.

like image 27
Tevo D Avatar answered Sep 19 '22 07:09

Tevo D