I have a code:
static short Sum(short a, short b)
{
return a + b;
}
And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!
It's just the way the language is defined. The + operator on integer types is defined for:
static uint op +(uint x, uint y)
static int op +(int x, int y)
static ulong op +(ulong x, ulong y)
static long op +(long x, long y)
Operands are promoted as required.
Now as for the reasons why it's defined that way - I don't know, to be honest. I don't buy the argument of "because it could overflow" - that would suggest that byte + byte
should be defined to return short
, and that int + int
should return long
, neither of which is true.
I've heard somewhere that it could be performance related, but I wouldn't like to say for sure. (Perhaps processors typically only provide integer operations on 32 and 64 bit integers?)
Either way, it doesn't really matter why it's the case - it's just the rules of the language.
Note that the compound assignment operators have an implicit conversion back to the relevant type, so you can write:
short x = 10;
short y = 20;
x += y;
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