#define st(x) do { x } while (__LINE__ == -1)的用法

此文章为笔记

#define st(x)      do { x } while (__LINE__ == -1)

__LINE__ 是个宏,它代表当前代码在源文件的行号,它是大于0的,所以__LINE__ == -1 等同于0,化简为:

#define st(x)      do { x } while (0)

Example:

#define a(x) if(x) { printf("%s\n", "OK"); }
int i = 1;
if(0)
    a(i);
else
    printf("%s\n", "KO");

Will expand to something equivalent to:

if(0)
{
    if(x)
    {
        printf("%s\n", "OK");
    }
    else printf("%s\n", "KO");
}

However if you define a(x) as:

#define a(x) st(if(x) { printf("%s\n", "OK"); })

it will work, expanding to:

if(0)
{
    do
    {
        if(x)
        {
            printf("%s\n", "OK");
        }
    }
    while(0);
}
else printf("%s\n", "KO");

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*(必填)