Multiplication for types smaller than int yields an int

  • Thread starter Thread starter Javier Estrada
  • Start date Start date
J

Javier Estrada

When multiplying two sbyte, byte, short, ushort, the
result is an int.

It seems to me that the language should leave the result
alone, otherwise let the user decide whether to use a
checked expression.

Can someone offer any insight for this design decision?

Regards,

Javier

Please respond to the newsgroup so everybody can benefit
from the answer.
 
Javier said:
When multiplying two sbyte, byte, short, ushort, the
result is an int.

It seems to me that the language should leave the result
alone, otherwise let the user decide whether to use a
checked expression.

Can someone offer any insight for this design decision?

IIRC, arithmetic operation results on 32 bit CPUs are always 32 bits, for
operands <= 32 bits.
BTW, in C++ we have a similar situation with the difference that the
conversion to the result type is implicit.

Regards,

Andreas
 
Javier said:
It seems to me that the compiler should hide the CPU
architecture.

Maybe, but that would be surprising for C++ programmers at which C# is
aimed. Moreover, some operations on byte or short values would overflow.
Consider the following situation:

byte x = 17;
byte y = 16;

byte result = x * y / 2;

x * y will yield a value greater than 255, but the division by 2 puts the
result back in the range of a byte. IIUC, then you would rather see result
holding an incorrect value?

Of course, you can argue similarly in the following situation:

uint x = 65537;
uint y = 65536;

uint result = x * y / 2;

Here, result will indeed hold an incorrect value, but most ex-C++
programmers will know that and convert the operands to ulong before applying
the operation.
When you say that in C++ the result type is implicit do
you mean implicitly and int or implicitly the type that
its supposed to be--from my description?

For integer operands <= 32 bits C++ will always calculate intermediate
results with 32 bits. However, in the end when the intermediate result is
assigned to a variable < 32 bits an explicit cast is not necessary. Some
compilers will issue a warning though (e.g. MSVC7.1 does so on warning level
4).

HTH,

Andreas
 
For integer operands <= 32 bits C++ will always calculate intermediate
results with 32 bits. However, in the end when the intermediate result is
assigned to a variable < 32 bits an explicit cast is not necessary.

Sorry, that is of course wrong. C++ integer types do not have
guaranteed sizes. So, more correctly:

For integer operands <= int (i.e. char, short, int), C++ will always
calculate intermediate results with int. However, in the end when the
intermediate result is assigned to a variable < int an explicit cast
is not necessary.

On most (if not all) platforms, a C++ int has as many bits as the data
bus, i.e. 32 on PCs.

Regards,

Andreas
 
Back
Top