programing

C 멀티 라인 매크로 : do / while (0) vs scope block [duplicate]

new-time 2020. 5. 24. 22:26
반응형

C 멀티 라인 매크로 : do / while (0) vs scope block [duplicate]


가능한 중복 :
매크로를 정의 할 때 while (0)을 어떻게 사용합니까?
C / C ++ 매크로에 때때로 의미없는 do / while 및 if / else 문이있는 이유는 무엇입니까?
{…} 동안 (0) 무엇을 위해 좋은가?

나는 do / while (0) 루프 안에 싸인 여러 줄의 C 매크로를 보았습니다.

#FOO 정의 \
  하다 { \
    do_stuff_here \
    do_more_stuff \
  } 동안 (0)

기본 블록을 사용하는 대신 코드를 작성하면 어떤 이점이 있습니까?

#FOO 정의 \
  {\
    do_stuff_here \
    do_more_stuff \
  }

http://bytes.com/groups/c/219859-do-while-0-macro-substitutions

안드레이 타라 세 비치 :'do / while'버전을 사용하는 전체 아이디어는 복합 명령문이 아닌 일반 명령문으로 확장되는 매크로를 작성하는 것입니다. 이는 모든 컨텍스트에서 일반 함수를 사용하여 함수 스타일 매크로를 균일하게 사용하기 위해 수행됩니다.다음 코드 스케치를 고려하십시오.

if (<condition>)
  foo(a);
else
  bar(a);

여기서 'foo'와 'bar'는 일반적인 기능입니다. 이제 함수 'foo'를 위의 자연의 매크로로 바꾸고 싶다고 상상해보십시오.

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

이제 매크로가 두 번째 접근 방식 ( '{'및 '}')에 따라 정의 된 경우 'if'의 'true'분기가 이제 복합 명령문으로 표시되므로 코드가 더 이상 컴파일되지 않습니다. 그리고 당신이 ';' 이 복합 명령문 후 전체 'if'문을 완료하여 'else'분기를 고아 (따라서 컴파일 오류).이 문제를 해결하는 한 가지 방법은 ';' 매크로 "호출"후

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

이것은 예상대로 컴파일되고 작동하지만 균일하지 않습니다. 보다 우아한 해결책은 매크로가 복합 문이 아닌 일반 문으로 확장되도록하는 것입니다. 이를 달성하는 한 가지 방법은 다음과 같이 매크로를 정의하는 것입니다.

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

이제이 코드

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

아무런 문제없이 컴파일됩니다.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

참고URL : https://stackoverflow.com/questions/1067226/c-multi-line-macro-do-while0-vs-scope-block

반응형