为什么我通过乘以两个短整数得到一个负数?

我有一个作业,我有以下代码摘录:

/*OOOOOHHHHH I've just noticed instead of an int here should be an *short int* I will just left it as it is because too many users saw it already.*/ int y=511, z=512; y=y*z; printf("Output: %d\n", y); 

这给了我Output: -512 。 在我的任务中,我应该解释原因。 所以我很确定这是因为隐式转换(纠正我,如果我错了:))从将int值赋给short int发生。 但我的导师说,事情刚刚发生,我想是“三轮”。 我找不到任何关于它的事情,我正在看这个video ,那个人解释(25:00)几乎和我告诉我的导师一样。

编辑:

这是我的完整代码:

 #include  int main() { short int y=511, z=512; y = y*z; printf("%zu\n", sizeof(int)); printf("%zu\n", sizeof(short int)); printf("Y: %d\n", y); return 0; } 

这是我如何编译它:

 gcc -pedantic -std=c99 -Wall -Wextra -o hallo hallo.c 

我没有错误也没有警告。 但是如果我使用-Wconversion标志编译它,如下所示:

 gcc -pedantic -std=c99 -Wall -Wextra -Wconversion -o hallo hallo.c 

我收到以下警告:

 hallo.c: In function 'main': hallo.c:7:7: warning: conversion to 'short int' from 'int' may alter its value [-Wconversion] 

转换确实发生了吗?

intshort int的转换是实现定义的。 你得到结果的原因是你的实现只是截断你的数字:

  decimal | binary -----------+------------------------ 511 | 1 1111 1111 512 | 10 0000 0000 511 * 512 | 11 1111 1110 0000 0000 

由于您似乎具有16位short int类型,因此11 1111 1110 0000 0000变为1111 1110 0000 0000 ,这是-512的二进制补码表示:

  decimal | binary (x) | ~x | -x == ~x + 1 ---------+---------------------+---------------------+--------------------- 512 | 0000 0010 0000 0000 | 1111 1101 1111 1111 | 1111 1110 0000 0000