void 함수에서 복귀
함수에서 반환하는 더 올바른 방법은 다음과 같습니다.
void function() {
// blah some code
}
또는
void function() {
// blah some code
return;
}
두 번째 방법의 근거 :
- 개발자의 의도를 더 명확하게 표현합니다.
- 사전 컴파일 시간에 함수 종료를 감지하는 데 도움이됩니다.
이러한 시나리오가 있다고 가정 해 보겠습니다. 함수가 많고 해당 함수 끝에 코드를 삽입해야합니다. 그러나 어떤 이유로 당신은 그러한 엄청난 양의 기능을 원하지 않거나 수정할 수 없습니다. 그것에 대해 무엇을 할 수 있습니까? Return
& macro
가 작동합니다. 예 :
#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
void 함수에서 반환되는 유일한 이유는 일부 조건문으로 인해 일찍 종료하는 것입니다.
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.
The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.
I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?
I would be severly annoyed by such a pointless extra return
statement at the end of a void
function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.
An old question, but I'll answer anyway. The answer to the actual question asked is that the bare return is redundant and should be left out.
Furthermore, the suggested value is false for the following reason:
if (ret<0) return;
Redefining a C reserved word as a macro is a bad idea on the face of it, but this particular suggestion is simply unsupportable, both as an argument and as code.
참고URL : https://stackoverflow.com/questions/9003283/returning-from-a-void-function
'program story' 카테고리의 다른 글
Linq 구별-개수 (0) | 2020.12.07 |
---|---|
Rails 3 : yield / content_for 일부 기본값? (0) | 2020.12.07 |
ExpandableListView -UnsupportedOperationException : addView (View, LayoutParams)는 AdapterView에서 지원되지 않습니다. (0) | 2020.12.07 |
계속하려면 아무 키나 누르십시오. (0) | 2020.12.07 |
생성자를 호출하여 개체 다시 초기화 (0) | 2020.12.06 |