Typecasting from int to long int

13,505

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.

Share:
13,505
Siraj Alam
Author by

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, 2022

Comments

  • Siraj Alam
    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 that long and long int are identical. So the statements c = 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 and long int are identical, so why there is error in the above two statements ?

  • Irminsul
    Irminsul almost 8 years
    Good one. Should mention that (long int) is the C-way while static_cast<long int> is the C++ one.
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 8 years
    @Benoit: Both are valid in C++.
  • Irminsul
    Irminsul almost 8 years
    You 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
    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
    Irminsul almost 8 years
    Thanks ! That's exactly the kind of explanation and 'fight' I was looking for.
  • cigien
    cigien over 2 years
    This is already covered in the previous answer.