[英]Declare variable in if statement (ANSI C)
有没有办法在if 语句中声明变量(仅使用ANSI C )?
例子:
if(int variable = some_function())
{
return 1;
}
不,你不能那样做。
您可以做的是仅为if
创建一个复合语句(匿名或悬挂块)
{
int variable;
variable = some_function();
if (variable) return 1;
}
/* variable is out of scope here */
请注意,对于这个简单的情况,您可以调用函数作为if
的条件(不需要额外的变量)
if (some_function()) return 1;
从GCC 扩展:
括在括号中的复合语句在 GNU C 中可能显示为表达式。这允许您在表达式中使用循环、开关和局部变量。 回想一下,复合语句是由大括号括起来的语句序列; 在这个结构中,括号围绕着大括号。 例如:
({ int y = foo (); int z; if (y > 0) z = y; else z = - y; z; })
是
foo ()
。复合语句中的最后一件事应该是一个后跟分号的表达式; 此子表达式的值用作整个构造的值。 (如果您在大括号中最后使用某种其他类型的语句,则该构造的类型为
void
,因此实际上没有任何价值。)...
简化示例:
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.