当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Why "do ... while (0)" can't be replaced by simple curly brackets?

问题描述:

This question already has an answer here:

  • Why use apparently meaningless do-while and if-else statements in C/C++ macros?

    10 answers

网友答案:

It's the semicolon after the macro.

The macro is expanded to this instead:

if (argc == 1)
    {
        printf("hello ");       \
        printf("world!\n");     \
    };
else        // HERE, SYNTAX ERROR
    fprintf(stderr, "nope\n");
return 0;

Since there should be no semicolon between the body of an if-statement and an else-clause, it's a syntax error.
OTOH, a do-while loop allows (and needs) a semicolon.


The misconception regarding the compiler output can be easily avoided by just printing the real preprocessor output. That's possible by using

  • the -E switch of the gcc executable. From man 1 gcc:

-E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output.

  • the preprocessor directly in shape of the cpp executable.

Thanks to
- @dhke for correcting the line the error occurs at.
- @kakeh for the suggestion to view the preprocessor output beforehand.

网友答案:

Look CAREFULLY at how you call the macro.

You'd have to write

if (argc == 1)
    HELLO_WORLD() // NO SEMICOLON!!!!!!!
else
    fprintf(stderr, "nope\n");

which would be godawful because you could never replace the HELLO_WORLD macro with a real function.

分享给朋友:
您可能感兴趣的文章:
随机阅读: