Introduction to Programming Languages/Coercion

From Wikibooks, open books for an open world
< Introduction to Programming Languages
Jump to: navigation, search

Coercion[edit]

Many programming languages support the conversion of a value into another of a different data type. This kind of type conversions can be implicitly or explicitly made. Implicit conversion, which is also called coercion, is automatically done. Explicit conversion, which is also called casting, is performed by code instructions. This code treats a variable of one data type as if it belongs to a different data type. The languages that support implicit conversion define the rules that will be automatically applied when primitive compatible values are involved. The C code below illustrates implicit and explicit coercion. In line 2 the int constant 3 is automatically converted to double before assignment (implicit coercion). An explicit coercion is performed by involving the destination type with parenthesis, which is done in line 3.

1 double x, y;
2 x = 3;            // implicitly coercion (coercion)
3 y = (double) 5;   // explicitly coercion (casting)

A function is considered a polymorphic one when it is permited to perform implicit or explicit parameter coercion. If the same is valid for operands, the related operator is considered a polymorphic operator. Below, a piece of C++ code exemplifies these polymorphic expressions.

#include <iostream>
void f(double x) {     // polymorphic function
  std::cout << x << std::endl;
}

int main() {
  double a = 5 + 6.3;  // polymorphic operator
  std::cout << a << std::endl;

  f(5);
  f((double) 6);
}

Overloading · Parametric Polymorphism