gpt4 book ai didi

c - C 中的隐式 "declaration-in-instantiation"?

转载 作者:太空狗 更新时间:2023-10-29 15:25:54 26 4
gpt4 key购买 nike

是否可以在初始化中隐式声明变量?或许是这样的:

struct S
{
void *a;
void *b;
};

struct S test = {&(int), &(float) };

void testfunc (void)
{
*(test.a) = -2;
*(test.b) = 1.3;
}

优点(在我看来):

  1. 显式声明不需要额外的行
  2. 隐式变量在结构中受到保护,没有外部访问。

最佳答案

是的,这是可能的,因为 C99。您的猜测非常接近;但即使您打算稍后分配另一个值,也需要提供花括号初始化程序:

struct S test = { &(int){0}, &(float){0} };

此功能称为 compound literal .复合文字是左值。

请注意,您的 testfunc 包含一个错误;由于 a 的类型为 void *,因此您不能编写 *(test.a)。您可以将 S 更改为 int *a; float *b;,否则你必须在写作时进行转换,例如*(int *)test.a = 5;.

关于c - C 中的隐式 "declaration-in-instantiation"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39244757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com