Why do I get a negative number by multiplying two

2019-08-31 11:01发布

问题:

I had an assignment where i had the following code excerpt:

/*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);

Which gives me Output: -512. In my assignment I should explain why. So i was pretty sure it is because of the implicit conversion( correct me if I'm wrong:) ) happening from assigning an int value to an short int. But my tutor said that thing just happened called something with "triple round" i guess. I couldn't find anything about it and I'm watching a this video and the guy explains(25:00) almost the same thing I told my tutor.

Edit:

Here is my full code:

#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;
}

Here is how i compile it:

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

I get no errors and no warnings. But if i compile it with -Wconversion flag enabled as follows:

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

I get the following warning:

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

So the conversion does happen right?

回答1:

The conversion from int to short int is implementation defined. The reason you get the result you do is that your implementation is just truncating your number:

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

Since you appear to have a 16-bit short int type, that 11 1111 1110 0000 0000 becomes just 1111 1110 0000 0000, which is the two's complement representation of -512:

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