(int) ch vs. int (ch): Are they different syntaxes for the same?

In C ++, (int) ch is equivalent to int (ch).

If not, then what's the difference?

+6
c ++ casting
source share
8 answers

This is one and the same as well as (int)(ch) . In C ++, it is usually preferable to use a named cast to clarify your intentions:

  • Use static_cast to transfer between primitive types of different sizes or labels, for example. static_cast<char>(anInteger) .
  • Use dynamic_cast to dump the base class into a derived class (only for polymorphic types), for example. dynamic_cast<Derived *>(aBasePtr) .
  • Use reinterpret_cast to translate between pointers of different types or between a pointer and an integer, for example. reinterpret_cast<uintptr_t>(somePtr) .
  • Use const_cast to remove const or volatile qualifiers from variables ( VERY DANGEROUS ), for example. const_cast<char *>(aConstantPointer) .
+19
source share

int(x) is called a functional style that is different from the standard one, and is the same as in the C-style in all respects (for POD) [5.2.3]:

If the list of expressions is a single expression, the type conversion expression is equivalent (in the definition and, if defined by sense) to the corresponding expression (5.4).

+10
source share

They are the same.

+3
source share

Conrad Rudolph is right. But keep in mind that

  • (int) x <- valid syntax in C and C ++
  • (int *) x <- - valid syntax in C and C ++
  • int (x) <- - valid in C ++, but gives a syntax error in C
  • int * (x) <- gives a syntax error in both C and C ++
+3
source share

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 (for example, if T = int) or to a constructor call (if T is a class type). An example of my own experience, when it was useful, was that I switched from using native types for intermediate results of calculations to integers of arbitrary precision, which are implemented as a class.

+2
source share

The first is C style, and the second is C ++ style.

In C ++, use the C ++ style.

+1
source share

It is worth noting that both casting styles are deprecated in C ++, in favor of the longer, more specific casting methods listed in Adam Rosenfield's answer.

+1
source share

If you want to be super nasty, then if you write something like:

 #define int(x) 1 

Then (int) x has the value you expect, while int (x) will be 1 for any value of x. However, if anyone ever did this, you probably should have hurt them. I can also well believe that somewhere in the standard you are forbidden to #defining keywords, although I can’t find it right now.

In addition, a very stupid, special case, then, as mentioned earlier, [5.3.2] says that they are the same for POD

-one
source share

All Articles