gpt4 book ai didi

c - 为什么这种隐式转换(在不同指针类型之间)有效?

转载 作者:太空狗 更新时间:2023-10-29 16:37:59 24 4
gpt4 key购买 nike

我发现自己处于以下情况:

#include <stdio.h>

typedef struct T1 { int id; } T1;
typedef struct T2 { int id; } T2;

void f(T1 *ptr) { printf("f called\n"); }

int main(void)
{
T2 obj;
T2 *ptr = &obj;
f(ptr); // shouldn't this be a compilation error ?
return 0;
}

当然,这在 C++ 中是无效的,但在 C 中,程序 prints “叫”。这怎么有效?

编辑

(以防万一不清楚)该程序仍将 compile如果 T2 “在结构上”不同,则运行,例如

typedef struct T2 { double cc[23]; } T2;

最佳答案

这是无效的,如果你想强制执行符合标准的代码,使用正确的标志进行编译很重要,例如 gccclang 以下标志:

-std=c99 -pedantic-errors

将为 C99 标准要求的诊断生成错误,类似地,您可以为 C11 使用 -std=c11。这将从 gcc ( see it live ) 生成以下错误:

error: passing argument 1 of 'f' from incompatible pointer type

编译器具有扩展并允许像 implicit int 这样的功能由于遗留代码,了解其中的区别很重要。参见 gcc document: Language Standards Supported by GCC了解更多详情。

查看这实际上无效的快速方法是转到 Rationale for International Standard—Programming Languages—C在处理转换的 6.3.2.3 Pointers 部分告诉我们:

It is invalid to convert a pointer to an object of any type to a pointer to an object of a different type without an explicit cast.

稍长的路径需要我们转到 draft C99 standard 6.5.2.2 函数调用部分说(强调我的前进):

If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment,

然后如果我们转到 6.5.16 部分 赋值运算符 其中说:

One of the following shall hold

对于指针我们有:

  • both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • one operand is a pointer to an object or incomplete 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;
  • the left operand is a pointer and the right is a null pointer constant;

我们看到这些情况都不成立,因此转换无效。

关于c - 为什么这种隐式转换(在不同指针类型之间)有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27127914/

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