본문 바로가기
컴퓨터/프로그래밍 언어

do while(0) 문을 쓰는 이유.

by Luyin 2014. 5. 10.

그냥 매크로 여러줄을 선언할 것을 왜 do while(0) 문 안에 넣어서 지정하는 것일까? 

그 이유는 간단히 설명하면 아래와 같다.


'다중 구문의 매크로함수 전체가 도중에 멈추지 않고 실행되게 하기 위해서이다.'


무슨 말이냐 하면 아래의 코드를 보면 이해 할 것이다.


1. 정의된 매크로

#define FOO(x) \

printf("arg is %s\n", x);\

do_something_useful(x);


2. 사용 예

if(blah == 2)

FOO(blah);


3. 실제 내용

if(blah == 2)

printf("arg is %s\n", blah);

do_something_useful(blah);


4. 수정된 매크로

#define FOO(x) do {\

printf("arg is %s\n", x);\

do_something_useful(x);

while(0)


5. 수정된 매크로가 적용된 결과

if(blah == 2)

do{

printf("arg is %s\n", blah);

do_something_useful(blah);

}while(0);