4

When looking over some code from a friend's project, I recently saw syntax that looked like this.

#include <iostream>

int main(){
    std::cout<< int(32.5/5)  << std::endl;
}

When you run the above code, you get 6, which is the expected value if the use of int functions like a cast.

However, I have never seen this syntax before and I could not find documentation for it on the web. I also did an experiment and noticed that this syntax is not valid in C.

Can someone explain the meaning of this syntax with documentation references?

M.M
  • 138,810
  • 21
  • 208
  • 365
merlin2011
  • 71,677
  • 44
  • 195
  • 329

1 Answers1

9

This is not a constructor call or a "function". There is no "int function".

This is functional cast notation; it's just a cast.

It's the same as (int)(32.5/5) (in this particular case).

And, no, C does not have it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 2
    I think the fact that you could write a reasonable answer to this question implies that it is not exactly a terrible fit for our format. I agree that I could have phrased it better but you understood the intent fairly clearly. – merlin2011 Feb 14 '15 at 20:12
  • @merlin2011: Actually I was a bit naughty, because I did not answer your question (which _is_ a bad fit) but some imaginary modified version of your question! But, yes, I gave you the benefit of the doubt. Now perhaps you can edit the question to make it fit the site's model, retaining your intent..? – Lightness Races in Orbit Feb 14 '15 at 22:03
  • I have edited the question. Let me know if the edit is up to scratch. :) – merlin2011 Feb 14 '15 at 22:10
  • Adding to this a bit, the same syntax can involve a constructor call depending on the type. For example if `T` is a template parameter then `T(32.5/5);` is valid, and instantiating with a class type will call a constructor, and instantiating with `int` won't. – M.M Feb 14 '15 at 22:43
  • @MattMcNabb: Right, but that's a factor of how explicit conversions work, not of what this syntax specifically does. If you catch my drift. – Lightness Races in Orbit Feb 14 '15 at 23:35