سؤال

I am getting error on following lines " Type mismatch: cannot convert from int to short"

short a;
a=09;

but not on

a=9;

why is it so.

هل كانت مفيدة؟

المحلول

Using a 0 before a number means it's an octal. You can only use it from 00 to 07, so you cannot make the conversion (it also does not work with int, since it's out of range, even if it looks like it's trying to make an implicit casting).

09 simply is a number that does not exist, computationally speaking.

نصائح أخرى

To answer your question specifically, that's a compiler peculiarity. A different compiler (maybe just a different version) would give you a somewhat less confusing error, such as integer number too large: 09 instead of tripping on the cast, which in your case is not even possible, since the number is invalid.

The issue in your code is that you are trying to define an integer (or a short in your case) in an octal notation because you are starting the number with a leading 0. In octal notation digits can only be between 0 and 7. So an octal number written as 09 does not exist.

So both things combined confused your compiler a bit.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top