Terminal L in C
In C, are the follow开发者_开发知识库ing equivalent:
long int x = 3L;
(notice the L
)
and
long int x = 3
They seem to be the same. In case they are, which one should be used? Should the L
be specified explicitly?
If they are different, what is the difference?
3.14L
is a long double
literal, while 3.14
is a double
literal. It won't make much difference in this case, since both are being used to initialize a long int. The result will be 3.
EDIT:
Ok, 3L
is a long
literal, while 3
is an int
literal. It still won't make much difference, since the int
will be "promoted" to a long. The result will be the same in both cases.
EDIT 2: One place it might make a difference is something like this:
printf("%ld\n", 123);
This is undefined behavior, since the format string specifies a long
and only an int
is being passed. This would be correct:
printf("%ld\n", 123L);
A decimal integer constant without suffix has - depending on its value - the type int
, long
, long long
, or possibly an implementation-defined extended signed integer type with range greater than long long
.
Adding the L
suffix means the type will be at least long
, the LL
suffix means that the type will be at least long long
.
If you use the constant to initialize a variable, adding a suffix makes no difference, as the value will be converted to the target-type anyway. However, the type of the constant may well be relevant in more complex expressions as it affects operator semantics, argument promotion and possibly other things I didn't think of right now. For example, assuming a 16-bit int
type,
long foo = 42 << 20;
invokes undefined behaviour, whereas
long bar = 42L << 20;
is well-defined.
精彩评论