gpt4 book ai didi

c - 为什么在表达式的括号中使用类型声明?

转载 作者:行者123 更新时间:2023-11-30 20:50:44 30 4
gpt4 key购买 nike

我正在尝试通过逐行分解一些源代码来学习 C。我遇到了(我认为是)表达式(?)内括号内的类型声明,我想知道为什么要这样做。以下是一些让我感到困惑的例子。

static void foo(int a)
{
(void)a; // Why the parantheses and void inside of it?
}
struct bar *a = (struct bar *)calloc(1, sizeof(struct bar));
// ^ Why declare struct bar pointer?

根据第一个假设,我想这与强制结果或值与声明匹配有关,但在函数示例的情况下,为什么不直接执行 foo(void)

此外,如果这个模式有一个名称(因为我很难命名或描述正在发生的事情),那么我以后搜索它会更容易。

谢谢!

最佳答案

声明

(void)a;

引用 a,然后您不会收到编译器警告 a 是未使用的变量。

(void) 只是必需的语法。

你的第二个问题

struct bar *a;

将定义一个指向该类型的struct的变量。但同时,您正在初始化它

struct bar *a = (struct bar *)calloc(1, sizeof(struct bar));

这与

相同
struct bar *a;
a = (struct bar *)calloc(1, sizeof(struct bar));

但在 C 中,可以说最好不要转换 calloc 和其他分配函数的返回值。我会将该行写为

a = calloc(1, sizeof *a);

关于c - 为什么在表达式的括号中使用类型声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40453834/

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