Typecasting from int to long int
Just because they are the same type doesn't mean you can literally exchange the characters in your source code.
The syntax is confused by a T()
cast when T
has a space in it.
Write c = a * (long int)b
instead.
Siraj Alam
Computer Science is in my DNA. You can share my knowledge on my personal blog garbagevalue designed and developed by myself.
Updated on June 14, 2022Comments
-
Siraj Alam almost 2 years
Recently I searched the difference between
int
,long int
,long
, ... and so on. And I got the answer from here. And I found thatlong
andlong int
are identical. So the statementsc = a *long(b);
and
c = a * long int (b)
should be same in the program
int main() { int a = 10, b = 20; long int c; c = a *long(b); cout << c; return 0; }
But the second statement is showing an error
[Error] expected primary-expression before 'long'
So I just want to know, if
long
andlong int
are identical, so why there is error in the above two statements ? -
Irminsul almost 8 yearsGood one. Should mention that
(long int)
is the C-way whilestatic_cast<long int>
is the C++ one. -
Lightness Races in Orbit almost 8 years@Benoit: Both are valid in C++.
-
Irminsul almost 8 yearsYou seem really experienced in c++. I wonder what do you mean by 'valid'. Working ? Acceptable ? or perfectly suitable ? All references that i found said 'do not use C-like cast in c++'. I can't open a question because it will be tagged as duplicate but i read a lot of your posts and i am really curious about your opinion on that.
-
Lightness Races in Orbit almost 8 years@Benoit: It's not vastly idiomatic, particularly for complex types, but it's completely fine for an arithmetic type as far as I'm concerned. Some people will insist on
static_cast
for absolutely everything but in this case it's unnecessarily verbose. In fact this came up just the other day: stackoverflow.com/a/37996003/560648 -
Irminsul almost 8 yearsThanks ! That's exactly the kind of explanation and 'fight' I was looking for.
-
cigien over 2 yearsThis is already covered in the previous answer.