从void函数返回 [英] Returning from a void function
问题描述
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:
- 它可以更清楚地表达开发人员的意图。
- 它有助于在预编译时检测函数结束:
- It expresses developer intentions more clearly.
- It helps detecting function end at pre-compile time:
假设你有这样的场景 - 你有一堆函数,你必须在这些函数的末尾注入一些代码。但出于某些原因,您不希望/或不能修改如此巨大的功能。你能做些什么? 返回
&例如: macro
>
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;
}
推荐答案
随你选。提供空的 return;
语句允许从某处返回 void
函数中的 return 除了结束之外。没有其他理由我相信。
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.
这篇关于从void函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!