gpt4 book ai didi

c - A a = (A) b; 中是否需要显式类型转换?

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

我正在阅读一些开源的 C 代码,并多次遇到 A a = (A) b; 类型转换。例如,

static void hexdump(const void* pv, int len)
{
const unsigned char* p = (const unsigned char*) pv;
// some other code
}

A a = (A) b;代码主要发生在b是指针时,void *指针最常见。我有 C++ 背景。我认为在 C++ 中,赋值运算符 = 会自动处理类型转换?因为它已经知道 aA 类型。

C 中是否需要显式类型转换?

最佳答案

不,在 C 中从 void*char* 的转换(这是一个 common example 来解释它们的不同之处!)是隐式的,因此不需要转换(然后错误,因为如果您错误地将 char 更改为 int,它可能会隐藏一个问题。

引用 K&R 的“The C Programming Language,第 2 版”(§A.6.8):

Any pointer to an object may be converted to type void* without loss of information. If the result is converted back to the original pointer type, the original pointer is recovered. Unlike the pointer-to-pointer conversions discussed in Par.A.6.6, which generally require an explicit cast, pointers may be assigned to and from pointers of type void*, and may be compared with them.

请注意“如果结果被转换回原始指针类型”,因为这很关键:如果您使用的不是 char* 而不是 int* 那么它可能是错误的,因为内存对齐。

来自 C99 标准 (§6.3.2.3) 关于何时可以进行转换:

A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

现在让我们看看什么时候可以隐式(感谢 mafso 的快速搜索),来自 C11 (n1570) §6.5.4p3:

Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.

然后§6.5.16.1:

One of the following shall hold: [...] the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right

关于c - A a = (A) b; 中是否需要显式类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408150/

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