0

Suppose I have a floating point number x and I want to convert it into an integer. Is there any difference between int(x) and (int)x in C++. I am new to C++ coming from Python background and naturally I tried int(x) to convert x to an integer but reading about C++ I came across type-casting i.e. (int)x and in this case it also works.

I was wondering what's the difference between these two approaches and in a wider context which one to use where?

float x = 5.5;
cout<<int(x)<<endl; //outputs 5
cout<<(int)x<<endl; //outputs 5
ATK
  • 358
  • 3
  • 17
  • 1
    IIRC `int(x);` is declaration for x. `(int)x;` is a type cast whose result is then ignored. But in your case, either has the same meaning, a type cast. – Tanveer Badar Sep 12 '19 at 17:54
  • 2
    The only real difference is `int(x)` can't use types with spaces in their name. `long long(x)` is invalid. `(long long)x` on the other hand is. – NathanOliver Sep 12 '19 at 18:13
  • @NathanOliver that sounds like a defect in the standard. Clearly they should amend it to allow `(long long)(x)`. – Hong Ooi Sep 12 '19 at 18:17
  • @HongOoi `(long long)(x)` is also valid. You just can't do `long long(x)` or `unsigned int(x)` or any other 2+ word type – NathanOliver Sep 12 '19 at 18:30
  • but `using ll = long long; ll(x);` is fine. – Jarod42 Sep 12 '19 at 18:36
  • @NathanOliver I was trying to troll the C++ committee but the C++ committee has trolled me :( – Hong Ooi Sep 12 '19 at 18:48

0 Answers0