为什么要在表达式的括号中使用类型声明?
Why use type declarations in paretheses for expressions?
我试图通过逐行分解一些源代码来学习 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
和其他分配函数中转换 return 值。我会把那行写成
a = calloc(1, sizeof *a);
它们是 c 风格的转换。不要在 C++ 中使用它们。有一种情况需要在 C++ 中使用 c 风格的转换,但在我的整个职业生涯中,我从未 运行 需要这种需求。
强制转换告诉编译器一种类型的变量具有不同的类型。
将表达式转换为 void
告诉编译器您不关心结果。当您告诉编译器对所有事情都抱怨时,这可以避免警告。
我试图通过逐行分解一些源代码来学习 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
和其他分配函数中转换 return 值。我会把那行写成
a = calloc(1, sizeof *a);
它们是 c 风格的转换。不要在 C++ 中使用它们。有一种情况需要在 C++ 中使用 c 风格的转换,但在我的整个职业生涯中,我从未 运行 需要这种需求。
强制转换告诉编译器一种类型的变量具有不同的类型。
将表达式转换为 void
告诉编译器您不关心结果。当您告诉编译器对所有事情都抱怨时,这可以避免警告。