do
{
	// do something
} while (false)

1번만 실행되는 코드를 저렇게 묶어놨길래 scope 때문에 저랬나 싶었다.

do
{
	if (A)
	{
		break;
	}
	if (B)
	{
		break;
	}
} while(false)

// do something finally

보니깐 goto 대신 scope 를 빠져 나가기 위해서 사용하는 스타일이었다.

#define DO_SOMETHINGS(X) \
	DO_FUNC_A(X); \
	DO_FUNC_B(X);

DO_SOMETHINGS(a); // DO_FUNC_A -> DO_FUNC_B

// if true, DO_FUNC_A -> DO_FUNC_B -> DO_FUNC_C
// if false, DO_FUNC_B -> DO_FUNC_C ????
if (IS_TRUE(a))
	DO_SOMETHINGS(a); 
DO_FUNC_C(a);

do...while(false) 를 사용하는 또 다른 용도로는 if  문 같은 곳에서 의도치 않은 흐름을 막을 수 있다. 위와 같은 경우 if 문에서 false 일 경우 의도치 않게 B -> C 가 호출된다.

#define DO_SOMETHINGS(X) \
	do \
	{ \
		DO_FUNC_A(X); \
		DO_FUNC_B(X); \
	} while(false);

위와 같은 상황을 피하고자 do while(false) 로 묶어서 선언한다.

참고 :

https://stackoverflow.com/questions/2314066/do-whilefalse

 

do {...} while(false)

I was looking at some code by an individual and noticed he seems to have a pattern in his functions: <return-type> function(<params>) { <initialization> do { <main code...

stackoverflow.com

https://still.tistory.com/79

 

goto 대신에 do { ... } while (false)를 사용한 에러처리

C/C++ 코딩을 하다보면 흔히 아래와 같은 에러처리 코드를 만나게 된다. ... if (!condition1)    goto cleanup; ... if (!condition2)    goto cleanup; ... if (!condition3)    goto cleanup; ... if (!c..

still.tistory.com

https://grandstayner.tistory.com/entry/C-do-while-false-%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-%EC%9D%B4%EC%9C%A0-12

 

C++ - do ~ while (false) 를 사용하는 이유 (1/2)

리눅스 커널 소스를 살펴보다가 헤더쪽의 매크로에서 “do { … } while(0)” 와 같은 것이 많이 쓰인 것을 보았다. 당연히 { … } 이 한번만 실행되고 끝나는 건데, 왜 이렇게 했을까 궁금해서 찾아

grandstayner.tistory.com

 

728x90

+ Recent posts