在同一行中投放两次 [英] Casting twice in the same line

查看:54
本文介绍了在同一行中投放两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中看到了这段代码。

I saw this code in project.

b 的类型为 void *

void *b = ...;
int a = (int) (unsigned long) b;

这行毫无意义吗?我的意思是,在所有情况下,它是否与 a =(int)b 相同?

Is this line pointless? I mean, it this same as a = (int) b in all cases?

推荐答案

这可能避免在64位Unix系统上的编译器警告,其中 unsigned long 是64位数量,因此足够容纳指针,但是 int 是一个32位的数量,不足以容纳指针。强制转换为(无符号长)保留地址的所有位;随后的转换为 int 会丢弃该地址的高32位,但默认情况下不会收到警告。

This probably avoids a compiler warning on 64-bit Unix systems where unsigned long is a 64-bit quantity and hence big enough to hold a pointer, but int is a 32-bit quantity that is not big enough to hold a pointer. The cast to (unsigned long) preserves all the bits of the address; the subsequent cast to int throws away the high-order 32-bits of the address, but does so without getting a warning by default.

要演示:

int main(void)
{
    void *b = (void *)0x12345678;
    int   a = (int)(unsigned long)b;
    int   c = (int)b;
    return a + c;
}

$ gcc -O3 -g -std=c99 -Wall -Wextra -c ar.c
ar.c: In function ‘main’:
ar.c:5:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
$

在Mac OS X 10.8.4上使用GCC 4.7.1,默认为64位编译。

Using GCC 4.7.1 on Mac OS X 10.8.4, defaulting to 64-bit compilation.

这很有趣推测将使用地址的一部分值做什么。

It is interesting to speculate what will be done with the 'part of an address' value.

这篇关于在同一行中投放两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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