gpt4 book ai didi

c - 如何在函数参数中声明变量

转载 作者:太空宇宙 更新时间:2023-11-04 06:53:01 25 4
gpt4 key购买 nike

我需要在函数参数中声明一个变量。请建议使用的语法?

我有这样的东西:

#include <stdio.h>

int foo (int *a)
{
printf ("%d\n", *a);
}

int main (void)
{
foo (&(int){int a=1});
return 0;
}

GCC 失败并显示消息:

$ gcc a.c
a.c: In function 'main':
a.c:10: error: expected expression before '{' token

作为一个选项,我可以像这样使用未命名的变量(same question at russian version of Stack Overflow):

foo(&(int) { 1 });

它有效,但有趣的是为什么编译器接受 {1} 但不接受 {int a=1}

最佳答案

您可以使用复合字面量 - 我怀疑这就是您尝试过的方法,您几乎做对了:

foo (&(int){1});

这绝不是一个“常数”,我不知道你是怎么想到的。

请注意,复合文字仅具有本地(“自动”)存储持续时间 - 如果调用 block 超出范围,则复合文字也会。

关于c - 如何在函数参数中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48537078/

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