In some C# code I have seen staments like this:
float someFloat = 57f;
I want to know why we should use literals like f
in the above case?.
Generally, literals are a notation for representing a fixed value in source code. They can also be defined as raw values or data given in variables or constants. Python has different types of literal such as: String literals.
You can use literals as operands in order to introduce data into your program. The literal is a special type of relocatable term. It behaves like a symbol in that it represents data. However, it is a special kind of term because it also is used to define the constant specified by the literal.
Constant values that are typed in the program as a part of the source code are called literals. Literals can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings, and Boolean Values.
String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
Mainly so the compiler knows exactly what we mean - in particular for overload resolution:
Foo(57f);
should that call Foo(int)
/ Foo(float)
/ Foo(decimal)
?
Actually, I don't like remembering things - an alternative is:
float someFloat = (float)57;
this is not a runtime cast - it is identical (at the IL level) to 57f
. The only time it is subtly different is with decimal
s with extra precision:
decimal someDecimal = (decimal)57.0; // same as 57M, not 57.0M (scale is different)
The "f" above is a type suffix. This tells the compiler the exact type of the literal provided. This is used so the compiler can allocate the appropriate amount of storage (precision) for the literal. By default, floating point literals are given storage for a "double." If you add "f" as a suffix, the literal will only get the storage for a float, which will have less accuracy.
double d = 50.1234; // given double storage
double d = 50.1234f; // given float storage, which might lose precision compared to double
By default, a real numeric literal on the right-hand side of the assignment operator is treated as double. Therefore, to initialize a float variable use the suffix f or F, for example:
float x = 3.5F;
If you don't use the suffix in the previous declaration, you will get a compilation error because you are attempting to store a double value into a float variable.
From MSDN: float
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