Use Do...while (0) in the C language macro definition

Source: Internet
Author: User

Recently see the C language project in the macro definition used Do...while (0), feel is a knowledge point, special to summarize.

First look at this sentence:do{...} while (0) is the only constructor in C that allows you to define a macro that always works the same way, so that no matter how the macro is used (especially if the statement that calls the macro is not surrounded by curly braces), the semicolon behind the macro is the same effect. the meaning of this sentence is that all statements contained in the macro definition using Do...while (0) are a block of code that is not affected by {};

See an example:

#include <stdio.h> #include <stdlib.h> #define TEST (p)                                     do                                          {                                               if (p!=null)                                 {free                                               (p);                                    printf ("Free success!\n");              }                                           P=null;                                 } while (0) int main () {    int *p=null;    p= (int*) malloc (sizeof (int));    TEST (p);    printf ("---------done!---------\ n");    return 0;}

The function of this line is that the statement is not finished, and the next line is joined with the previous line.

Let's look at an example of error:

Macro definition: #define FOO (x) bar (x); Baz (x)

Then call: foo (x); This is based on the principle of macro substitution: bar (x); Baz (x); that's right!

But if so: if ()

Foo (x)

will be replaced by: if ()

Bar (x);

Baz (x); This is obviously not the same as what we want to do!

Why not use curly braces 直接 to surround a macro? Why do you have to use do/while (0) logic?

Follow the example above:

if()

{

     bar(wolf);      baz(wolf); };     //最后会添加;,在语法上是错误的!

Use Do...while (0) in the

C language macro definition

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.