Given y = y * z;
where all operands are type int16_t
and the values are 1024 * 65 = 66560,
then there are two possibilities:
- If your system is 8 or 16 bit, you will have 16 bit
int
type. There will be no type promotion of the operands since they are already 16 bits and you get a signed integer overflow, invoking undefined behavior. Since 16 bit signed integers can only store values up to 32767.
If your system is 32 bit, then both y
and z
are implicitly promoted (see Implicit type promotion rules) to type int
which is then 32 bits. The result of the multiplication is of type int
. The value 66560 will fit just fine.
You then convert this 32 bit int
to int16_t
upon assignment. The value will no longer fit - what will happen is an implementation-defined conversion from signed 32 to signed 16. (In theory your system may raise a signal here.)
In practice most systems will simply take the 66560 = 10400h and cut off the MS bytes, leaving you with 1024 = 400h.
In either case, the equation y = y * z;
is highly questionable given the size of the input values! This is to be regarded as a bug. You should use uint16_t
or int32_t
instead.
As for y / 3 * 3 - 3 * y / 3
, it will be 1024 / 3 * 3 - 3 * 1024 / 3
. All operands are integers and the operator associativity of multiplicative operators *
and /
is left-to-right.
So you get 341 * 3 - 3072 / 3
-> 1023 - 1024
= -1
.
As a side-note, you are using the wrong printf
conversion specifier. The most correct one for int16_t
is this:
#include <inttypes.h>
printf("1. Ausgabe: %"PRIi16 "\n", y);