I got shocked knowing that there are no arithmetic operator +
, -
, *
, /
, and %
for 8 and 16 bit integers in C#. I am reading "C# 5.0 Pocket Reference" on page 23 as follows.
The following code does not compile.
class Program
{
static void With16Bit()
{
short a = 1;
short b = 2;
short c = a + b;
Console.WriteLine(c);
}
static void With8Bit()
{
byte a = 1;
byte b = 2;
byte c = a + b;
Console.WriteLine(c);
}
static void Main(string[] args)
{
With8Bit();
With16Bit();
}
}
Why did the C# designers do it? What are their consideration about it?
& operator is not an arithmetic operator The basic arithmetic operations are addition, subtraction, multiplication, and division. There are more arithmetic operators like exponentiation, modulus operations, increment, decrement, etc. * - Multiplication operator. So, And operator is not an arithmetic operator.
Types of Arithmetic Operators in C: These are two types of Arithmetic Operators in C.
Integer division yields an integer result. For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division. The remainder operator is an integer operator that can be used only with integer operands.
Answer: True. Explanation: "+" is an arithmetic operator.
There are arithmetics with Int8, Int16; but the result is int32 and so you have to cast:
class Program
{
static void With16Bit()
{
short a = 1;
short b = 2;
short c = (short) (a + b); // <- cast, since short + short = int
Console.WriteLine(c);
}
static void With8Bit()
{
byte a = 1;
byte b = 2;
byte c = (byte) (a + b); // <- cast, since byte + byte = int
Console.WriteLine(c);
}
static void Main(string[] args)
{
With8Bit();
With16Bit();
}
}
Plese remember that when you perform addition operation on short
and byte
the default outcome would be Integer.
So the :
byte + byte = int
short + short = int
So if you want to get back the actual value you need to cast it back.
Try This:
short a = 1;
short b = 2;
short c =(short) (a + b);
Console.WriteLine(c);
byte a = 1;
byte b = 2;
byte c =(byte) (a + b);
Console.WriteLine(c);
From The Source:
This Behaviour is because the designers have not considered that
byte
andshort
as actual numbers ,but they have considered them as only sequence ofbits
. so performing arithmetic operations on them does not make any sense so if that is the case int and long would serve the purpose.
From kek444 answer
All operations with integral numbers smaller than Int32 are widened to 32 bits
before calculation by default. The reason why the result is Int32 is
simply to leave it as it is after calculation. If you check the
MSIL arithmetic opcodes, the only integral numeric type they operate
with are Int32 and Int64. It's "by design".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With