19

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.

piero borrelli
  • 737
  • 2
  • 9
  • 20
  • 13
    Are you sure you meant to write `int b = 5.5;`? – T.C. Jan 30 '15 at 12:22
  • 3
    Implicit type conversions are called *coercions* (although I don't think it's 100% universal. See [here](http://en.wikipedia.org/wiki/Type_conversion "Wikipedia article for type conversions.")). – Bakuriu Jan 30 '15 at 16:16

5 Answers5

20

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.

Community
  • 1
  • 1
Columbo
  • 60,038
  • 8
  • 155
  • 203
18

"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!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 3
    If it's misused so often, perhaps it's the definition that's incorrect, not its usage. After all, natural language is defined by its actual usages *(despite what grammar-nazis would have you believe)*. Personally, I've heard the term "implicit cast" plenty of times, and never thought of it as incorrect. – BlueRaja - Danny Pflughoeft Jan 30 '15 at 18:18
  • 4
    @BlueRaja-DannyPflughoeft: No. We are talking about terminology defined in an International Standard, not some colloquialism on the streets. This is _science_, not just using your "natural language" down the pub. The entire point of the standard is to unambiguously define the means to describe the language, and in this case that so happens to include what "cast" means. Every time you've heard that term, it _is_ wrong. It's as wrong as saying "you're correct and wrong". – Lightness Races in Orbit Jan 30 '15 at 18:23
  • 8
    Even if the term "cast" is defined in the C++ standard as an explicit conversion, calling "implicit cast" incorrect is still too strong. Natural language is not that cut-and-dry. I would say "imprecise" or "a colloquialism". However, where in the standard does it even say that? – BlueRaja - Danny Pflughoeft Jan 30 '15 at 18:27
  • 2
    @BlueRaja-DannyPflughoeft: The entire section on explicit conversions is subtitled "cast notation". That's what it means. I will never buy into this "you can say the exact opposite and cause a 100% contradictory phrase and it's okay because 'natural language'" nonsense. We have a specification for a reason, as I already said. Yes, "implicit cast" is wrong. I can't stop you from uttering it, but it's wrong. It expands to "implicit explicit conversion" which is completely meaningless. You might as well start calling it "igglewigglewoggle" and it'll be about as useful a phrase. – Lightness Races in Orbit Jan 30 '15 at 18:37
  • 4
    "cast notation" is a qualified noun, describing the specific notation that section describes. That is different from defining the verb "casting" itself. – BlueRaja - Danny Pflughoeft Jan 30 '15 at 18:41
  • 1
    @BlueRaja-DannyPflughoeft: Are you suggesting that "casting" is something that is not the thing defined by "cast notation"? You simply cannot use cast notation to perform an implicit conversion. It is not possible. Said another way, you cannot use a cast to perform an implicit conversion. There is no such thing as an "implicit cast". – Lightness Races in Orbit Jan 30 '15 at 18:51
  • 1
    Besides, if we were to start defining technical language on how it's misused across the world, we would have literally no idea what anybody else is talking about by now. Ignorance is rife but fortunately we have _standards_ and _specifications_ to unambiguously define things for us. – Lightness Races in Orbit Jan 30 '15 at 18:54
  • 1
    Yes, I am suggesting that "casting" and "casting notation" are two different things. "Casting notation" refers to the notation used to cast, which obviously only applies to explicit casts, since *by definition* implicit casts have no notation. That doesn't mean they are not casts, though. – BlueRaja - Danny Pflughoeft Jan 30 '15 at 21:37
  • Not to take part into that debate, but as a piece of trivia : in French (and probably other languages), "cast" has been borrowed from English and its sense widened to all type changes, because it's short and easy to pronounce and morph (caster, castable...). Retrotranslation may be one source of such misuses. – Quentin Jan 30 '15 at 22:07
  • 1
    @Quentin Highly irrelevant. Similar confusion exists with "undefined behavior" because people ignore the intended meaning from the International Standard. It doesn't matter what the word means outside of the language. It's precisely defined within the Standard, it's meaning is unambiguous. –  Jan 30 '15 at 22:09
  • @remyabel Let's say "tangential". I find it interesting not only to recognise a mistake, but also to know where it came from. But again, this is just trivia. – Quentin Jan 30 '15 at 22:15
  • 2
    I'm with LRiO on this one - people mistake "type cast" with "type conversion" - "cast" is *always* explicit, see e.g. Casting conversion (§5.5) converts the type of an expression to a type explicitly specified by a cast operator (§15.16). (from JLS) - we have "cast operator", "casting conversion", "cast notation"... OTOH, we have "implicit conversions", "widening conversions" and "type promotions", http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html - I know this is a C++ question, but C++ spec is parallel to JLS in this one. No amount of misuse will make calling'em "casts" valid. –  Jan 30 '15 at 22:25
  • 2
    §5.1.2\18 makes reference to an implicit "cast" that occurs for `this` in a lambda expression. §12.3.1/2 also refers to "when casts are explicitly used", implying the existence of implicit casts. (Even so, I remain unconvinced that implicit conversions count as casts, it's likely these are mere oversights) – Mooing Duck Jan 30 '15 at 22:42
  • @MooingDuck 5.1.2\18 does not use the term "implicit cast" though. – Columbo Jan 30 '15 at 22:58
  • @Columbo: It doesn't use the word "implicit", but it does use the word "cast" in a context where the conversion is done implicitly. – Mooing Duck Jan 30 '15 at 23:28
  • @MooingDuck It's not the kind of implicity that we are talking about though. Essentially the cast is generated by the implementation, but that doesn't make it an implicit conversion. – Columbo Jan 30 '15 at 23:37
  • 1
    @Columbo: I fail to see the difference. It's not an explicit cast, it's implicit. It's done behind the scene by the compiler, 100% like all implicit conversions and 100% unlike all explicit conversions. – Mooing Duck Jan 30 '15 at 23:38
12

Widening (value-preserving) conversions — conversions whose results upon conversion back to its original type would give the original value — are generally done implicitly. This

char c = 'x'; 
int b = c;

is an implicit conversion. Explicit conversions are called casts.

int a = 1;
double sum = static_cast<double>(a) / b;

Here casting a into a double is explicitly done as both a and b are ints; without the cast no conversion would happen thereby leading to an integer division while a floating-point division may be preferred as it may be more precise. Casting one of the operands of / to double which will lead to the other getting implicitly converted to a double too, and thus the division (and its result) would now be floating-point.

Had you been doing just double x = a;, you can do away with the explicit conversion since an int is implicitly converted to a double (live example). From the C++11 standard, N3337 draft

— if either operand is double, the other shall be converted to double.

See here for a complete list of implicit conversions performed.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • 3
    C++ does all sorts of non-value-preserving conversions implicitly, too. – T.C. Jan 30 '15 at 12:24
  • 1
    I didn't say otherwise. – legends2k Jan 30 '15 at 12:25
  • 1
    But casting a into double wouldn't be `(double) a`? – Phate01 Jan 30 '15 at 12:56
  • Generally, new style casts are preferred: `static_cast( a )`; alternatively, for creating a new object, function style casts: `double( a )`. And in your example, if `a` is an `int`, it will _not_ be implicitly converted to a `double`; this is one of the cases where you really do need an explicit type conversion. – James Kanze Jan 30 '15 at 13:02
  • @legends2k: If `b` is an `int` (even though it's initialized with a `double` literal) there is nothing to cause `a` to be converted to `double`. – Fred Larson Jan 30 '15 at 16:22
  • @FredLarson Aah, you guys are taking about the `/` operator while I was taking about the assignment operation where an `int` (literal or variable) assigned to a `double`, would be implicitly converted to a `double`. Fixed the answer to avoid confusion. – legends2k Jan 30 '15 at 18:17
2

Casting is explicit conversion of variables in an expression. Like this

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

Whereas this

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

.. is an example of implicit type conversion(or coercion sometimes) where datatypes are promoted from one type to another implicitly [like char to int]

Have a look at this article for more insight.

Cheers!

nalinc
  • 7,375
  • 24
  • 33
1

This is not casting but standard conversion as C++ standard n3337 states in

§ 4 Standard conversions

4.5 Integer promotions

1) A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

4pie0
  • 29,204
  • 9
  • 82
  • 118