什么是分配一个无符号的变量有符号值的交易? [英] What is the deal with assigning an unsigned variable to a signed value?

查看:215
本文介绍了什么是分配一个无符号的变量有符号值的交易?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code,我看有很多,我看到这样的事情发生的地方:结果

This code I am looking at has a lot of places where I see things like this happening:

char *functionName(char *passedVariable)
{
    unsigned char *newVariable = (char* ) passedVariable;

这是为什么正在做?我总是尽量在使用符号/无符号一致的,因为我知道,这两者之间的切换可能会造成问题,但是这似乎开发商并没有在意。

Why is this being done? I always try to be consistent in the use of signed/unsigned, because I know that switching between the two can cause problems, but this developer doesn't seem to care.

推荐答案

更改指针类型是不是一个真正的问题,该地址仍然有效。
然而除preting尖头数据符号/无符号使得当且仅当...签名的数据为负值的差值。因此,在你的例子,如果你的字符的始终是肯定的,那么它的确定,否则就不是。

Changing the pointer type is not really an issue, this address will still be valid. However interpreting the pointed data as signed/unsigned makes a difference if and only if... the signed data is negative. So in your example if your char's are always positive, then it's ok, otherwise it is not.

符号/无符号的类型转换的例子:

Example of signed/unsigned casts:

char c = 42;
char d = -42;
unsigned char cu = c;
unsigned char du = d;

printf("c  %d\n", c);
printf("cu %d\n", cu);
printf("d  %d\n", d);
printf("du %d\n", du);

输出:

c  42
cu 42
d  -42
du 214

这篇关于什么是分配一个无符号的变量有符号值的交易?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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