In C++, is (int) ch equivalent to int(ch).
If not, what's the difference?
In C++, is (int) ch equivalent to int(ch).
If not, what's the difference?
The first is the C style, while the second is the C++ style.
In C++, use the C++ style.
They are the same thing, and also the same as (int)(ch)
. In C++, it's generally preferred to use a named cast to clarify your intentions:
static_cast
to cast between primitive types of different sizes or signednesses, e.g. static_cast<char>(anInteger)
.dynamic_cast
to downcast a base class to a derived class (polymorphic types only), e.g. dynamic_cast<Derived *>(aBasePtr)
.reinterpret_cast
to cast between pointers of different types or between a pointer and an integer, e.g. reinterpret_cast<uintptr_t>(somePtr)
.const_cast
to remove the const
or volatile
qualifiers from variables (VERY DANGEROUS), e.g. const_cast<char *>(aConstantPointer)
.int(x)
is called function-style cast by the standard and is the same as the C-style cast in every regard (for POD) [5.2.3]:
If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).
If you want to be super-nasty, then if you write something like:
#define int(x) 1
Then (int)x has the meaning you expect, while int(x) will be 1 for any value of x. However, if anyone ever did this, you should probably kill them. I can also quite believe that somewhere in the standard you are forbidden from #defining keywords, although I can't find it right now.
Except for that, very stupid, special case, then as said before, [5.3.2] says they are the same for PODs
Although the two syntaxes have the same meaning for int, the second, constructor-style syntax is more general because it can be used with other types in templates. That is, "T(x)" can be compiled into a conversion between primitive types (e.g., if T = int) or into a constructor call (if T is a class type). An example from my own experience where this was useful was when I switched from using native types for intermediate results of calculations to arbitrary-precision integers, which are implemented as a class.
It's worth noting that both styles of casting are deprecated in C++, in favor of the longer, more specific casting methods listed in Adam Rosenfield's answer.