c - 在 void* 函数中返回 float

标签 c function pointers return

我正在学习指针的工作原理,但我不明白这段代码中的一件事。 在 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.

因此,您不能合法地将 intfloat 分配给指针类型 - 这是违反约束的。

关于c - 在 void* 函数中返回 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290855/

相关文章:

c - 如何为字符串指针数组分配内存,以及其他问题

c++ - 在编译时为变量赋值

C/C++ : Disable mouse in Linux (X11 - xinput)

c - linux 中的 readdir 在哪里?

python - 如何测试一个函数被调用了多少次

c - "install"函数在 C 语法中意味着什么?

c - 将整数分配/转换为指针

c - 无需 Curses 即可对控制台图形进行动画处理

python - 无法理解函数行为 - isprime()

c++ - 如何在 C++ 中释放内存