Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-casting in C++

Tags:

c++

casting

I'm studying C++ by two months using the book : Programming principles and practice using C++, and now I wanted to clarify some doubts about my casting. When I am performing an implicit conversion, for example :

char c = 'a'; 
int b = c; 

Here the value of c is implicitly converted to int type without using any explicit operator. Is this considered casting ? or its considered casting just when I have to performe an explicit conversion like in :

int a = 10; 
int b = 5.5; 
double sum = double (a) / b; 

I know it may sound a stupid question but I just wanted to be sure about conversions.

like image 387
piero borrelli Avatar asked Jan 30 '15 12:01

piero borrelli


People also ask

What is type type casting?

In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer.

What is type of conversion in C?

In this case, the double value is automatically converted to integer value 34. This type of conversion is known as implicit type conversion. In C, there are two types of type conversion: Implicit Conversion. Explicit Conversion.


2 Answers

As mentioned in other answers, casts are written explicitly. The standard refers to them as explicit type conversions; [expr.cast]/2:

An explicit type conversion can be expressed using functional notation (5.2.3), a type conversion operator (dynamic_cast, static_cast, reinterpret_cast, const_cast), or the cast notation.

There are three kinds of expressions that we call casts, mentioned in the above quote:

  • (T)expr. In the standard this form is called the cast notation of explicit type conversion and is also commonly referred to as a C-style cast (as it is the syntax used in and inherited from C). (double) a is an example.

  • T(expr). This is the functional notation (also called function-style cast). Often used for creating temporaries of class type, e.g. std::string("Hello World"). double(a) is also a function-style cast.

  • And last but not least, the so-called type conversion operators static_cast<T>(expr), reinterpret_cast, const_cast and dynamic_cast. These are the most explicit notations and are individually more restricted.

The use of all these is covered in this Q/A.

Every other conversion performed is not called a cast.

like image 174
Columbo Avatar answered Oct 02 '22 03:10

Columbo


"Casting" is only when you perform an explicit conversion.

That being said, you will find the term misused all across the internet and in various teams!

like image 24
Lightness Races in Orbit Avatar answered Oct 02 '22 04:10

Lightness Races in Orbit