oru*_*pov 0 c c++ type-conversion implicit-conversion
我有一个作业,我有以下代码摘录:
/*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);
Run Code Online (Sandbox Code Playgroud)
哪能给我Output: -512.在我的任务中,我应该解释原因.所以我很确定这是因为隐式转换(纠正我,如果我错了:))从将int值赋给short int发生.但是我的导师说,事情恰好发生了,我想是"三轮".我找不到任何关于它的事情,我正在看这个视频,那个人解释(25:00)几乎和我告诉我的导师一样.
这是我的完整代码:
#include <stdio.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
这是我如何编译它:
gcc -pedantic -std=c99 -Wall -Wextra -o hallo hallo.c
Run Code Online (Sandbox Code Playgroud)
我没有错误也没有警告.但是如果我使用-Wconversion标志编译它,如下所示:
gcc -pedantic -std=c99 -Wall -Wextra -Wconversion -o hallo hallo.c
Run Code Online (Sandbox Code Playgroud)
我收到以下警告:
hallo.c: In function ‘main’:
hallo.c:7:7: warning: conversion to ‘short int’ from ‘int’ may alter its value [-Wconversion]
Run Code Online (Sandbox Code Playgroud)
转换确实发生了吗?
Car*_*rum 10
转换int为short int是实现定义的.你得到结果的原因是你的实现只是截断你的数字:
decimal | binary
-----------+------------------------
511 | 1 1111 1111
512 | 10 0000 0000
511 * 512 | 11 1111 1110 0000 0000
Run Code Online (Sandbox Code Playgroud)
既然你似乎有一个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
Run Code Online (Sandbox Code Playgroud)