在 ANSI C 中,在 if 语句中声明变量。

6

有没有办法在if语句中声明变量(仅使用ANSI C)?

示例:

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

4
不行。在C语言中不允许这样做。 - BLUEPIXY
1
https://dev59.com/EWoy5IYBdhLWcg3wkOwK - Jorge Cavaiuolo
5
根据 ANSI C 语法,if 语句的语法为 IF '(' expression ')' statementexpression 不能解析为 declaration,因此无法像您的示例中那样在 if 语句中放置一个声明。 - Random Davis
不要使用经典的type var = value格式来严格声明变量。 - sjsam
@RandomDavis,该语法已经过时(但特定的生产环境没有更改)。请注意,该语法中的“IF”是指“if”关键字(“IF”是普通标识符)。ISO C标准中的语法为**if** ( expression ) statement或**if** ( expression ) statement else statement - Keith Thompson
直到我意识到在检查错误标志时代码变得多么重复,我才开始欣赏这种结构的价值。 - Sridhar Sarnobat
2个回答

10
不,你不能这样做。
你可以创建一个if语句的复合语句(匿名或悬挂块)。请参考此处
    {
        int variable;
        variable = some_function();
        if (variable) return 1;
    }
    /* variable is out of scope here */

请注意,对于这种简单的情况,您可以将函数作为if的条件调用(无需额外的变量)。
if (some_function()) return 1;

如果你指的是匿名大括号,我很高兴。我认为它们被低估了,并且是重构的一个很好的第一步。 - Sridhar Sarnobat
1
标准将它们称为“复合语句”(C11 6.8.2)。 - pmg

2

来自GCC扩展:

A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression. Recall that a compound statement is a sequence of statements surrounded by braces; in this construct, parentheses go around the braces. For example:

({ int y = foo (); int z;
   if (y > 0) z = y;
   else z = - y;
   z; })

is a valid (though slightly more complex than necessary) expression for the absolute value of foo ().

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void, and thus effectively no value.)...

简单示例:

#include <stdio.h>
    
int main()
{
    if (({int a = 1; a;}))
        printf("Hello World: TRUE");
    else
        printf("Hello World: FALSE");

    return 0;
}

// output:
// Hello World: TRUE

#include <stdio.h>

int main()
{
    if (({int a = 0; a;}))
        printf("Hello World: TRUE");
    else
        printf("Hello World: FALSE");

    return 0;
}
// output:
// Hello World: FALSE

有人真的这样使用吗?是的!据我所知,Linux内核通过这种扩展简化了代码。

/* SPDX-License-Identifier: GPL-2.0-only */
#define __get_user(x, ptr)                      \
({                                  \
    int __gu_err = 0;                       \
    __get_user_error((x), (ptr), __gu_err);             \
    __gu_err;                           \
})

#define unsafe_op_wrap(op, err) do { if (unlikely(op)) goto err; } while (0)
#define unsafe_get_user(x,p,e) unsafe_op_wrap(__get_user(x,p),e)

https://elixir.bootlin.com/linux/latest/source/include/linux/uaccess.h#L365


有趣的是,尽管你可能无法从“then”语句中访问在测试表达式中声明的变量。 - Nick Treleaven

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接