printf 类型提升和符号扩展 [英] printf type promotion and sign extension

查看:55
本文介绍了printf 类型提升和符号扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 printf 和一般情况下如何进行类型提升感到困惑.我尝试了以下代码

I am confused about how type promotion happens in case of printf and in general. I tried the following code

unsigned char uc = 255
signed char sc = -128

printf("unsigned char value = %d \n", uc);
printf("signed char value = %d \n", sc);

这给出了以下输出:

unsigned char value = 255
signed char value = -128

这让我想知道促销实际上是如何进行的,以及是否会发生标志扩展.如果进行了符号扩展,则值 255 应打印为负值(-128 保持不变),如果未进行符号扩展,则应将 -128 打印为正值(255 保持不变).请解释.

This has left me wondering about how promotion actually takes place and whether a sign extension happens or not. If a sign extension is done then the value 255 should be printed as negative value (-128 remaining the same) and if no sign extension is done then -128 should have been printed as a positive value (255 remaining the same). Please explain.

推荐答案

如果进行了符号扩展,则值 255 应打印为负值

If a sign extension is done then the value 255 should be printed as negative value

这就是你错的地方 - unsigned char 类型的所有值,包括 255,都可以用 int 表示,所以升级为 int 来自 unsigned char 只是发生了没有任何有趣的事情.

This is where you're wrong - all values of type unsigned char including 255, can be represented in a int, so the promotion to int from unsigned char just happens without any funny business.

出现问题的地方是当有符号值必须转换(这与提升不同,并且为操作数创建通用类型)为无符号值.如果该有符号类型具有负值,则转换为无符号类型将更改该值.

Where problems occur is when a signed value must be converted (which is a different thing than promotion, and occurs to create a common type for operands) to an unsigned value. If that signed type has a negative value, then the conversion to an unsigned type will change the value.

综上所述,整数提升保值(包括符号),转换可以改变值.

In summary, integer promotion preserves value (including sign), conversion can change value.

这篇关于printf 类型提升和符号扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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