为什么在表达的paretheses中使用类型声明?

时间:2016-11-06 19:55:18

标签: c variable-declaration

我试图通过逐行分解一些源代码来学习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)

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

谢谢!

2 个答案:

答案 0 :(得分:2)

声明

(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);

答案 1 :(得分:1)

他们是c式演员。不要在C ++中使用它们。有一个off-case需要在C ++中使用c风格的转换,但我从未在整个职业生涯中遇到过需要。

强制转换告诉编译器一种类型的变量具有不同的类型。

将表达式转换为void告诉编译器您不关心结果。当你告诉你的编译器讨厌一切时,这可以避免警告。