为什么我可以投int和BOOL为void *,而不是浮动? [英] Why can I cast int and BOOL to void*, but not float?

查看:526
本文介绍了为什么我可以投int和BOOL为void *,而不是浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无效* 是C和衍生语言非常有用的特性。例如,它可以使用无效* 来的Objective-C的对象指针存储在C ++类。

void* is a useful feature of C and derivative languages. For example, it's possible to use void* to store objective-C object pointers in a C++ class.

我工作的一个类型转换框架和近期由于时间的限制有点懒 - 所以我用无效* ...这就是这个问题怎么来了:

I was working on a type conversion framework recently and due to time constraints was a little lazy - so I used void*... That's how this question came up:

我为什么INT强制转换为void *,但不能上浮到void *?

Why can I typecast int to void*, but not float to void* ?

推荐答案

BOOL不是C ++类型。它可能的typedef或某处定义的,并且在这些情况下,这将是一样中间体例如Windows,有这个在WINDEF.H:

BOOL is not a C++ type. It's probably typedef or defined somewhere, and in these cases, it would be the same as int. Windows, for example, has this in Windef.h:

    typedef int                 BOOL;

所以你的问题减少了,为什么你可以强制转换INT为void *,但不能上浮到void *?

so your question reduces to, why can you typecast int to void*, but not float to void*?

INT为void *是确定的,但一般不建议(和一些编译器会警告一下吧),因为它们本质上是在重新presentation相同。指针基本上是指向内存地址的整数。

int to void* is ok but generally not recommended (and some compilers will warn about it) because they are inherently the same in representation. A pointer is basically an integer that points to an address in memory.

浮动到void *也不行,因为浮点值的相互pretation和实际位重新presenting它是不同的。例如,如果你这样做:

float to void* is not ok because the interpretation of the float value and the actual bits representing it are different. For example, if you do:

   float x = 1.0;

它的作用是它集32位内存为00 00 80 3F(浮点值1.0 IEEE单precision实际重新presentation)。当你施放一个浮点数为void *,国米pretation是模糊的。你的意思是指向位置1在内存中的指针?或者你的意思是指向位置3f800000在内存中(假设小端)?指针

what it does is it sets the 32 bit memory to 00 00 80 3f (the actual representation of the float value 1.0 in IEEE single precision). When you cast a float to a void*, the interpretation is ambiguous. Do you mean the pointer that points to location 1 in memory? or do you mean the pointer that points to location 3f800000 (assuming little endian) in memory?

当然,如果你确信这你想要的两种情况下,总有一种方式来获得解决此问题。例如:

Of course, if you are sure which of the two cases you want, there is always a way to get around the problem. For example:

  void* u = (void*)((int)x);        // first case
  void* u = (void*)(((unsigned short*)(&x))[0] | (((unsigned int)((unsigned short*)(&x))[1]) << 16)); // second case

这篇关于为什么我可以投int和BOOL为void *,而不是浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆