What happens when operator is >,+ and two operands are unsigned int, char

huangapple go评论58阅读模式
英文:

What happens when operator is >,+ and two operands are unsigned int, char

问题

#include <stdio.h>

int main(void) {
	unsigned int n = 10;
	char m = -1;
	if (m < n)
		printf("m < n\n");
	else
		printf("m > n\n");
	printf("m + n = %u\n", m + n);
    return 0;
}

在我在Windows上的MinGW64中运行这段代码时,它会打印出"m > n"和"m + n = 9"。我不明白为什么会出现"m + n = 9"和"m > n"。

英文:
#include <stdio.h>

int main(void) {
	unsigned int n = 10;
	char m = -1;
	if (m < n)
		printf("m < n\n");
	else
		printf("m > n\n");
	printf("m + n = %u\n", m + n);
    return 0;
}

When I run this code in MinGW64 on windows. It prints "m > n","m + n = 9"
I can't understand why "m + n = 9" and "m > n".

答案1

得分: 2

我不明白为什么 "m + n = 9" 和 "m > n"。

只能比较兼容的整数,所以char被转换为unsigned int,其值是(假设32位整数和二进制补码负整数)0xffffffff,远远大于10

当你添加char时,它被转换为unsigned int并相加。这种转换后的负数的二进制补码相加会给出正确的值(它的行为类似于减法)。更多信息:https://en.wikipedia.org/wiki/Two%27s_complement

英文:

> I can't understand why "m + n = 9" and "m > n".

You can only compare compatible integers so char is being converted to unsigned int and its value is (assuming 32 bits integers and two complement negative integers) 0xffffffff which is much more than 10.

When you add char is converted to unsigned int and added. Two complements addition of such converted negative number gives the correct value (it acts like substraction). More information: https://en.wikipedia.org/wiki/Two%27s_complement

huangapple
  • 本文由 发表于 2023年2月8日 22:14:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定