Hi All,
Just something about C# that I've never truely understood
What do the suffixes (f, d, m, u, l etc) actually mean.
i.e what is the differnect (if any) between the following pairs of statements:
double x = 5 AND double x = 5d
double y = 1.2 AND double y = 1.2d
(and equivilent statements for floats and decimals)
Any simple explainations or references will be appreciated.
Thanks,
Sam.
SamPosted Aug 5, 2007, 7:17 AM
AlanPosted Aug 5, 2007, 7:07 AM
SamPosted Aug 5, 2007, 6:23 AM
Hi Alan & Mark,
Thank for your help!
Just one question:
With the statemnts
double x = 5 AND double x = 5d
Will the first one take longer to compile and/or longer to execute run-time?
Thanks,
Sam.
AlanPosted Aug 5, 2007, 5:51 AM
The type suffixes, as they are called, were inherited from C/C++ and what they do is to make the type of a numeric literal explicit or more explicit.
If you have an unadorned number with no decimal point (e.g. 5), then the compiler assumes it's an 'int' unless it won't fit within an int's range. The compiler then tries successively to regard it as a 'uint', 'long' and 'ulong'. If it won't fit in the ulong range, then the compiler throws an error.
If the number had been suffixed with L (or l), then the compiler would have assumed it was a long, or if it wouldn't fit in a long's range, a ulong.
Finally, if it had been suffixed with UL, then the compiler would have treated is as a ulong, period.
Similarly, if you have an unadorned numeric literal with a decimal point (e.g. 5.0), the compiler always treats it as a double.
However, if you have a numeric literal with or without a decimal point, suffixed by a D (or d), then the compiler treats that as a double as well. So to answer your original question, Sam, there's no difference at all between:
double y = 1.2 AND double y = 1.2d
where the 'd' is redundant because the number has a decimal point.
But, in the case of:
double x = 5 AND double x = 5d
the compiler assumes 5 is an int and then has to implicitly convert it to a double before assigning it to 'x'. However, no conversion is required in the second case because 5d is already a double.
The only way to create a float literal is by suffixing it with F(or f) or to create a decimal literal is by suffixing it with M(or m).
Type suffixes for integral types of 1 or 2 bytes are not supported.
ForgottenhartPosted Aug 4, 2007, 7:18 PM
They are called literals. Not sure really when to use them but it changes how the number is treated...
so
float x =123.45;
is treated different then
float x=123.45f;
float x-123.34F;
when the program is run.