Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

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

If not, what's the difference?

like image 846
108 Avatar asked Nov 04 '08 18:11

108


People also ask

What is the difference between * and & C++?

The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable.

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.


2 Answers

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:

  • Use static_cast to cast between primitive types of different sizes or signednesses, e.g. static_cast<char>(anInteger).
  • Use dynamic_cast to downcast a base class to a derived class (polymorphic types only), e.g. dynamic_cast<Derived *>(aBasePtr).
  • Use reinterpret_cast to cast between pointers of different types or between a pointer and an integer, e.g. reinterpret_cast<uintptr_t>(somePtr).
  • Use const_cast to remove the const or volatile qualifiers from variables (VERY DANGEROUS), e.g. const_cast<char *>(aConstantPointer).
like image 57
Adam Rosenfield Avatar answered Sep 24 '22 16:09

Adam Rosenfield


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).

like image 32
Konrad Rudolph Avatar answered Sep 24 '22 16:09

Konrad Rudolph