What is a diference between ((int) a) and (int(a))?
There's no difference between them in C++. However, C supports only the first cast operation.
See this example from tutorial:
double x = 10.3;
int y;
y = (int) x; // c-like cast notation
y = int (x); // functional notation
(type_name)identifier
(or more specifically (type_name)cast_expression
(6.5.4)) is a C-style cast. (int(a))
is syntactically invalid in C unless a
is a type. Then it could be part of a cast to a function taking type a
and returning int
, which would be a syntactically valid but semantically invalid cast, so useless too. int(a);
in C would be a declaration equivalent to int a;
.
C++ does support the int(a)
syntax for casts (the type name must be a single word; it doesn't work with e.g., unsigned long(a)
) on the grounds that int
(the type name) then becomes kind of like a type with a parametrized constructor (although even this is in C++ grouped together with C-style casts as a kind of a deprecated way of casting, and the more fine-grained/visible static_cast/reinterpret_cast/const_cast
casts are preferred).
The C++ syntax then appears to be quite interesting because this works (C++):
typedef int type_name;
type_name (a); //a declaration
a=0;
printf("%d\n", type_name(a)); //type_name(a) is a cast expr here