gpt4 book ai didi

C const 返回类型函数

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

以下代码中的“const”引起了什么行为,特别是强制转换:

const void *foo()
{
void *bar = NULL;

// Assign bar to some address here.

return (const void *)bar;
}

Actor 是必要的吗?编译器给出类型与返回类型不匹配的警告,除非我执行转换,但结果行为是否有任何不同?

最佳答案

Actor 不是必需的,甚至没有用。如果您不进行转换,C 不需要任何警告。

当需要const char * 返回值时,您可以返回char *。对于其他类型也是如此:当需要 const T * 时,您可以返回 T *

C 表示对于 return 语句:

(C99, 6.8.6.4p3) "If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function."

您可以将 char * 分配给 const char *(请注意,相反的情况无效)。C 表示指针赋值:

(C99, 6.5.16.1p1) "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; [...]"

关于C const 返回类型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089779/

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