Can a C macro contain temporary variables?

后端 未结 9 634
忘掉有多难
忘掉有多难 2020-12-16 15:25

I have a function that I need to macro\'ize. The function contains temp variables and I can\'t remember if there are any rules about use of temporary variables in macro subs

9条回答
  •  有刺的猬
    2020-12-16 16:03

    C macros are only (relatively simple) textual substitutions.

    So the question you are maybe asking is: can I create blocks (also called compound statements) in a function like in the example below?

    void foo(void)
    {
        int a = 42;
        {   
            int b = 42;
            {
                int c = 42; 
            } 
        }
    }
    

    and the answer is yes.

    Now as @DietrichEpp mentioned it in his answer, if the macro is a compound statement like in your example, it is a good practice to enclose the macro statements with do { ... } while (0) rather than just { ... }. The link below explains what situation the do { ... } while (0) in a macro tries to prevent:

    http://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html

    Also when you write a function-like macro always ask yourself if you have a real advantage of doing so because most often writing a function instead is better.

提交回复
热议问题