Two ways to write multi-statement macros 
Author Message
 Two ways to write multi-statement macros


Quote:
> I've noticed that whenever I see multi-statement macros in this
> newsgroup they're usually written with a "do {...} while(0)" construct
> to transform them into a single statement.  One of my colleagues asked
> a simple question that I can't answer: Why is this a better way to
> write multi-statement macros than simply enclosing the statements in
> braces without adding the "do" and "while(0)"?

The problem is that this program is not legal C:

    #include <stdio.h>
    #define macro(x) { if (x) puts("yes"); else puts("no"); puts("\n"); }

    int main()
    {
        char s[100];
        puts("Type some stuff > ");
        if ((gets(s))[0] == 'a')
            macro(1);
        else
            macro(0);
        return 0;
    }

whereas the same program with "do" and "while(0)" around the braces is
legal.  The idea of using "do { ... } while(0)" is that the macro be
legal in all statement contexts and nowhere else; i.e. that it should
behave as though the macro were in fact a function.

--
Gareth Rees



Mon, 30 Jun 1997 01:43:26 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. multi-statement cpp macro

2. multi-statement macros

3. Multi-statement macros (again)

4. lint problems with multi-statement macro

5. writing multi-line macros as expressions?

6. Difference between two different ways of doing things

7. macros and statements

8. Produce return statement with macros for arbitrary functions

9. macro using if and else statement

10. two if statements

11. offsetof macro doesn't work in case statements

12. Multi line function macros

 

 
Powered by phpBB® Forum Software