【问题标题】:Why is "int sum=ch1+ch2+ch2" not giving overflow when right-side operands are character variables & result >255? [duplicate]为什么“int sum=ch1+ch2+ch2”在右侧操作数为字符变量且结果 >255 时不会溢出? [复制]
【发布时间】:2013-05-16 11:25:18
【问题描述】:

在这个程序中,我试图将字符变量相加的结果分配给一个整数变量。我已经确保加法的大小大于 255。所以我预计右边会出现表达式溢出,甚至虽然结果是 362,但由于溢出,我希望在结果转换为 int 后分配 106,而不是 362。但奇怪的是 362 正在分配。

无论字符是有符号还是无符号,结果都是一样的。为什么没有溢出和分配362?因为加法时右边没有整数,所有操作数都是字符,我不希望他们被提升为int

#include<stdio.h>

int main(void)
{

unsigned char ch1='z',ch2='x'; //Same result for signed too
int sum=ch1+ch2+ch2;
printf("%d",sum);

}

【问题讨论】:

标签: c casting expression integer-promotion


【解决方案1】:

所有计算都以整数精度开始,因此您的语句将如下所示

int sum=(int)ch1+(int)ch2+(int)ch2;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多