but most importantly: avoid surprises when doing arithmetic; if you perform e.g. a multiplication like this:
int a;
...
long v=32767*a; // don't let the "long" fool you - 32767*a is evaluated as an int!
32767
is an int
literal (since it's small enough to fit an int
), a
is an int
, and the result will be an int
, even if you are assigning to a long
. This may be a problem if a
can be big enough to overflow your calculation; by specifying a long
literal, you guarantee that you'll perform a long
multiplication.
long v=32767L*a; // now we are doing all the math with longs
(This problem is actually way more frequent with division and FP literals, where often you have to specify double
or float
literals to get the intended "real division" behavior)
As @chris suggests, a way more frequent situation (of this same kind) arises when doing "big" bitshifts, e.g.:
long long mask=1<<53;
presents the same problem as above: 1
is an int
, 53
is an int
, the computation will be performed with int
s, resulting in overflow (although in this particular case any decent compiler will issue a warning); here the correct form would be:
long long mask=1LL<<53; // LL is the suffix for long long
L
去掉,尝试输入一个非常大的数字。那么你将会除以一个int
类型的数。这可能会引起问题。 - nhgrifint
,它们至少是int
(如果int
不够,则为long int
)。 - dyp