我正在学习指针的工作原理,但我不明白这段代码中的一件事。 在 void* 函数中返回 int 就像一个魅力,但返回 float 却没有。
#include <stdio.h>
void* square (const void* num);
int main() {
int x, sq_int;
x = 6;
sq_int = square(&x);
printf("%d squared is %d\n", x, sq_int);
return 0;
}
void* square (const void *num) {
int result;
result = (*(int *)num) * (*(int *)num);
return result;
}
#include <stdio.h>
void* square (const void* num);
int main() {
float x, sq_int;
x = 6;
sq_int = square(&x);
printf("%f squared is %f\n", x, sq_int);
return 0;
}
void* square (const void *num) {
float result;
result = (*(float *)num) * (*(float *)num);
return result;
}
最佳答案
您的两个函数都调用了 undefined behaviour ,因为返回类型和return
语句中表达式的类型不匹配。
至于为什么它似乎有效,请阅读未定义的行为。
就是说,在您将所有警告都视为错误的地方打开编译器警告,并且使用该设置此代码甚至不应该编译生成二进制文件,因为它包含应该生成诊断(警告)的约束违规.
相关说明:
引自 C11
,第 6.8.6.4 章
[...] 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.
关于简单赋值,来自章节 §6.5.16.1,简单赋值:
Constraints
One of the following shall hold:
- the left operand has atomic, qualified, or unqualified arithmetic type, and the right has arithmetic type;
- the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right;
- the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) 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;
- 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;
- the left operand is an atomic, qualified, or unqualified pointer, and the right is a null pointer constant; or
- the left operand has type atomic, qualified, or unqualified _Bool, and the right is a pointer.
因此,您不能合法地将 int
或 float
分配给指针类型 - 这是违反约束的。
关于c - 在 void* 函数中返回 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290855/