In c# when i say :
var s = 0;
what should be type of s
? it makes it int32
. then seems like var
is not usable for types like short
and others(?).
Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming. Helps to understand the fundamentals of Computer Theories.
C is a general purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. It was named 'C' because many of its features were derived from an earlier language called 'B'.
C may be best because it underpins most of the IT industry; without C, we wouldn't have Windows, macOS, Linux, Android, iOS, etc.; without C, we wouldn't have most of our language compilers. C may be best for efficient code generation. Very fast, compact code, ideal for embedded applications.
Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.
From the specification (§ 2.4.4.2):
If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.
So smaller types are not automatically inferred. You can add a cast to force such a smaller type:
var s = (short)0;
Look at this post here at StackOverflow.
You can specify a postfix for all numbers.
var i = 0;
var d = 0d;
var f = 0f;
var l = 0L;
var m = 0m;
As per the C# language standard, specifically §2.4.4.2 on integer literals:
The type of an integer literal is determined as follows:
- If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.- If the literal is suffixed by
U
oru
, it has the first of these types in which its value can be represented:uint
,ulong
.- If the literal is suffixed by
L
orl
, it has the first of these types in which its value can be represented:long
,ulong
.- If the literal is suffixed by
UL
,Ul
,uL
,ul
,LU
,Lu
,lU
, orlu
, it is of typeulong
.
The first rule is all that needs to be applied here. The literal 0
has no suffix and can be represented as type int
(or, in BCL terms, Int32
), so that's the type it has.
As you can infer from the above, to change the type of a literal, you can append a suffix to it. For example, the literal 0u
will be of type uint
. Alternatively, you could explicitly cast the literal to a different type; for example: (short)0
would cause the compiler to treat the literal as a short
.
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