Declare variable in if statement (ANSI C)

2020-07-27 05:20发布

Is there any way to declare variable in if statement (using ANSI C only) ?

Example:

if(int variable = some_function())
{
    return 1;
}

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-07-27 06:10

No, you cannot do that.

What you can do is create a block just for the if

    {
        int variable;
        variable = some_function();
        if (variable) return 1;
    }
    /* variable is out of scope here */

Note that for this simple case you can call the function as the condition of the if (no need for an extra variable)

if (some_function()) return 1;
查看更多
登录 后发表回答