Reputation: 3663
Do both declare & initiate a long integer?
I hope that's not too basic a question for this forum.I want to know if both the above statements achieve the same thing, ie declare a long integer variable num and initialize it to 24.Thanks.
Upvotes: 0
Views: 266
Reputation: 38183
Not exactly. long int
and int
are not guaranteed, but supposed to be different sizes.
long int num = 24;
this is safe, as 24
is an int, that is (implicitly) promoted to long int
.
int num = 24L;
this is not that safe IN GENERAL. 24L
defines a long int
, that is "truncated" to int
and if sizeof(int)
< sizeof(long int)
there COULD be a problem.
Why "IN GENERAL" and "COULD"? Because in this case, both things are the same and safe. But suppose do something like:
int num = xL;
where x
is a large number, that can fit in long int
but not in int
? Then you have an overflow.
Upvotes: 2
Reputation: 155485
One needs to distinguish between the type of the variable and the type of the constant used to initialize the variable.
The first declaration declares a long int
variable and initializes it to the value 24L
(which is what you get after casting the integer constant 24
to long int
). The second declaration declares an int
variable and initializes it to the value 24
(which is what you get after casting the long integer constant 24L
to int
.)
Upvotes: 1
Reputation: 108986
Are
long int num = 24;
andint num = 24L
the same?
They're different.
The first "creates" a variable of type long int
and implicitly converts the int
value 24 to the long int
type before assignment.
The second "creates" a variable of type int
and implicitly converts the long int
value 24 to the int
type before assignment.
Upvotes: 6
Reputation: 6084
No. the type of the variable is defined by the type of the variable is defined by the type to its left only:
long int num
declares the variable num
as a long int;int num
declares the variable num
as an int.Meanwhile, the right hand side of the equals is also defined independently.
24
is an int;24L
is a long intThe right hand side (in this case the 24
or 24L
) may then be forced (ie changed) to fit into the left hand side (in this case the variable num
), but never the other way round.
Upvotes: 1
Reputation: 13743
No, long int
declares a long int, and int
declares an int variable. The type of the variable never depends on what value it is "initialized" with (more precisely, assigned to). Hence the two declarations are the same if and only if the types long int
and int
are the same in your environment.
Upvotes: 4