Conceptcore
Type conversion
Also called type casting, casting, cast, coercion, type coercion, implicit conversion, explicit conversion.
A type conversion makes a value of one type from a value of another. Some keep the value, some lose part of it, and some fail. Languages differ in which ones need no cast.
- Applies to
- core-languages
Idea
A program often holds a value of one type and needs a value of another type. A count read from a file is text, and the code needs an integer. An integer takes part in a sum with a fraction, and the result must be a floating-point number. A type conversion makes the second value from the first.
Each language decides two things. First, which conversions happen implicitly, with no mark in the source. Second, what happens when the target type cannot hold the value. The Python program below shows four different answers.
print(1 + 2.5)
print(int(3.9), int(-3.9))
print(int("42") + 1)
try:
print("1" + 1)
except TypeError as error:
print("TypeError:", error)
3.5
3 -3
43
TypeError: can only concatenate str (not "int") to str
In 1 + 2.5, Python converts the integer to a float. In mixed arithmetic, the operand of the narrower type is widened to the type of the other operand.1 int(3.9) is an explicit conversion that drops the fraction. It truncates toward zero, so int(-3.9) is -3.2 int("42") does not change a representation. It parses text, and it can fail. "1" + 1 raises TypeError, because Python never converts between text and numbers on its own. JavaScript gives "11" for the same expression (see Pitfalls).
Two words name the two directions. A cast is the syntax for an explicit conversion, such as (int) x in C and Java or x as u8 in Rust. A coercion is a conversion that the compiler or the runtime inserts without a mark in the source. ALGOL 68 used "coercion" as a technical term in this sense.42
How it works
Four kinds of conversion
- Widening. The target type can represent every value of the source type, or at least its magnitude. An
intbecomes along, or afloatbecomes adouble. Most statically typed languages allow it implicitly. Java lists 19 widening primitive conversions, and none of them throws an exception at run time.12 - Narrowing. The target type cannot represent every value of the source type. A
longbecomes anint, or adoublebecomes anint. The language must say what happens to a value that does not fit. It can keep the low bits, saturate, throw an exception, or leave the behavior undefined. Most languages require a cast. - Reference conversion. The value stays the same object, and only its static type changes. An upcast from
CircletoShapeis always safe. A downcast fromShapetoCircleneeds a check at run time. Subtyping explains why the upcast is safe. - Parsing and formatting. Text becomes a number, or a number becomes text. This is a function with its own grammar, not a change of representation. Parsing can fail on input like
"42abc", so it needs a way to report an error.
What the machine does
A conversion to a wider integer type adds bits at the top. The Go spec states the rule for all integer conversions. A signed value is sign extended, an unsigned value is zero extended, and then the value is truncated to the size of the result type.21 So a conversion to a narrower integer type keeps the low bits. The Rust Reference gives the example 1234u16 as u8 == 210.25 The value 1234 is 0x04D2, and 0xD2 is 210.
A conversion between an integer and a floating-point number changes the encoding, and the processor has instructions for it. C, Java, C#, Go and Rust all truncate toward zero when they convert a float to an integer.613172125 They differ on a value that does not fit (see the table in Pitfalls).
An upcast of a reference changes nothing at run time. A checked downcast compares the run-time type of the object with the target type. On a mismatch it throws an exception or gives a null value.
C: integer promotions and the usual arithmetic conversions
C converts implicitly in all arithmetic. Two rules apply before an operation on integers.
- Integer promotions. This rule applies to a type with a rank lower than
int, such aschar,shortorunsigned char. A value of such a type becomes anintifintcan represent all values of the original type. Otherwise it becomes anunsigned int.3 So whenaandbareunsigned charvalues 200 and 100,a + bis 300 and not 44 (see the C example). - Usual arithmetic conversions. After the promotions, the two operands get a common type. If one operand is floating, the other converts to that floating type. If both are integers with the same signedness, the operand of lower rank converts to the higher rank. Suppose the unsigned operand has a rank greater than or equal to the rank of the signed operand. Then the signed operand converts to the unsigned type.4
The last rule causes a classic bug, shown in Pitfalls: -1 < 1u is false. A negative value converts to an unsigned type by repeated addition of one more than the maximum value of that type, so -1 becomes UINT_MAX.5 A conversion to a signed type that cannot hold the value gives an implementation-defined result or raises an implementation-defined signal.5 A conversion of a floating value whose integer part does not fit the integer type is undefined behavior.6
JavaScript: ToPrimitive, ToNumber and loose equality
JavaScript converts implicitly in almost every operator. The spec defines each conversion as an abstract operation.
- ToPrimitive turns an object into a primitive value. With the hint "number" it calls
valueOfand thentoString.8 - ToNumber turns a primitive into a number. A string that is not a valid numeric literal becomes
NaN. A string that is empty or holds only white space becomes 0.9 - ToBoolean gives false for
undefined,null,+0,-0,NaN,0nand the empty string. Every other value is true, including the string"0".11
The + operator first applies ToPrimitive to both operands. If either result is a string, it concatenates. Otherwise it converts both operands to numbers. A mix of a BigInt and a Number throws a TypeError.10 The other arithmetic operators always convert to numbers. So "3" + 1 is "31", and "3" - 1 is 2.
The == operator follows the IsLooselyEqual algorithm.7 If both operands have the same type, it compares them strictly. null and undefined are equal to each other and to no other value. If one operand is a number and the other is a string, the string converts to a number. A boolean operand converts to a number first. An object operand goes through ToPrimitive. The === operator never converts.
Java and C#: implicit widening, explicit narrowing
Java allows widening primitive conversions in assignments and method calls. A narrowing conversion needs a cast, with one exception. A constant expression of type int can be assigned to a byte, short or char variable if the value fits, as in byte theAnswer = 42;.15 A narrowing integer conversion keeps the low bits, so (byte) 200 is -56. A conversion from double to int maps NaN to 0 and saturates a value that is too large or too small.13
Three widening conversions in Java can lose precision: int to float, long to float and long to double. The result is the nearest value of the target type.12 A primitive value can also become an object. Boxing converts an int to an Integer.47
C# follows the same pattern. The implicit numeric conversions can lose precision, but never an order of magnitude.16 An explicit conversion from a floating type to an integral type rounds toward zero. If the result is out of range, a checked context throws OverflowException, and an unchecked context gives an unspecified value.17 An explicit integral conversion in an unchecked context discards the extra high bits.17 Non-constant expressions are unchecked by default. The compiler option CheckForOverflowUnderflow changes the default.18
Go and Rust: no implicit numeric conversion
Go requires an explicit conversion when an expression or an assignment mixes different numeric types. int32 and int are different types, even on a machine where they have the same size.22 Untyped constants are the exception. If one operand is an untyped constant and the other is not, the constant converts to the type of the other operand.46
Rust has no implicit numeric conversion either. It offers two explicit forms.
asis a primitive cast that never fails. Between integers it truncates or extends. From a float to an integer it rounds toward zero, saturates a value out of range, and maps NaN to 0.25FromandTryFromare traits.Fromis for conversions that cannot fail, such asi32toi64.TryFromis for conversions that can fail, and it returns aResult. Its documentation gives the example thatFromcannot convert ani64into ani32.26
C++: named casts and narrowing in braces
C++ keeps the conversions of C. It adds four named casts: static_cast, dynamic_cast, const_cast and reinterpret_cast. The C cast notation (T) x tries a list of these in order: const_cast, static_cast, static_cast then const_cast, reinterpret_cast, and reinterpret_cast then const_cast.30 The first interpretation in the list is used. A reader of (T) x cannot see which one it is.
dynamic_cast checks a downcast at run time. A failed cast to a pointer type gives a null pointer. A failed cast to a reference type throws std::bad_cast.29
Initialization with braces, called list-initialization, rejects narrowing conversions.27 A narrowing conversion includes a conversion from a floating type to an integer type. It also includes a conversion between integer types where the target cannot represent all values of the source. A constant source whose value fits is allowed.27 GCC reports a narrowing from a constant as an error, and a narrowing from a non-constant as a warning.28
Checked casts on references
Java checks a cast to a reference type at run time and throws ClassCastException when the object is not of the target type.14 C# throws InvalidCastException.19 The C# as operator returns null instead of throwing.20 Kotlin has the same pair. as throws ClassCastException, and as? returns null.32 In Go, x.(T) panics when x does not hold a T, and the form v, ok := x.(T) sets ok to false.24
The TypeScript as is different. It is a type assertion, and the compiler removes it. There is no check at run time, so a wrong assertion gives no exception and no null.45
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Numeric types are not subtypes of one another, so an Int needs toLong() or toDouble() to become a Long or a Double; as throws ClassCastException and as? returns null; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Native | CAST(value AS type) converts explicitly; the implicit conversions between text and numbers differ from one database engine to another. |
| Bash | Native | |
| PowerShell | Native | The left operand of an operator usually decides the type, and PowerShell converts the right operand to it; a cast such as [int]'43' converts explicitly; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no types to convert between. |
| CSS | Does not apply | Style rules have no conversions between types. |
| Regular expressions | Does not apply | A pattern matches text and has no other types. |
The example files show the main conversions in each language. The table gives the verdict for each tier 1 language.
| Language | Verdict | Implicit numeric conversion | Explicit forms |
|---|---|---|---|
| Python | native | int to float to complex in arithmetic1 |
int(), float(), str() |
| JavaScript | native | in almost every operator, and in ==710 |
Number(), String(), parseInt |
| TypeScript | native | as JavaScript at run time | as JavaScript; as checks nothing45 |
| Java | native | widening12 | (T) x, checked for references14 |
| C | native | promotions and usual arithmetic conversions34 | (T) x, strtol |
| C++ | native | as C; braces reject narrowing27 | static_cast, dynamic_cast and two more |
| C# | native | widening16 | (T) x, checked, as, int.Parse |
| Go | native | none, except for untyped constants2246 | T(x), x.(T), strconv |
| Rust | native | none | as, From, TryFrom, parse2526 |
| Kotlin | native | none in assignments and arguments31 | toInt(), toDouble(), as, as? |
| PowerShell | native | the left operand usually decides the type33 | [int]$x |
| Bash | native | a string is a number in arithmetic44 | $(( )) |
| SQL | native | the rules differ between engines | CAST(x AS T) |
| Regex | n/a | a pattern has no types | |
| HTML/CSS | n/a | markup and style rules have no conversions between types |
Kotlin numeric types are not subtypes of one another. A function that expects a Double does not accept an Int, and the code must call a conversion function such as toDouble(). In arithmetic, Kotlin does combine different numeric types. The sum of an Int and a Long is a Long.31
PowerShell converts in the other direction. The left operand of an operator usually decides the type, and PowerShell converts the right operand to it. 10 - ' 9 ' is 1, and '10' + '2' is '102'.33
Bash stores every value as a string. Inside an arithmetic expression, the value of a variable is evaluated as an arithmetic expression. A null or unset variable is 0, and a constant with a leading 0 is octal.44 So a typo in a variable name gives 0 and no error (see the Bash example).
print(1 + 2.5)
print(int(3.9), int(-3.9))
print(int(" 42 ") + 1, float("2.5") * 2)
print(str(7) + " days")
print(bool(""), bool("0"), bool([]), bool([0]))
print(float(2**53 + 1) == 2**53 + 1)
for text in ["42", "3.5", "4 2"]:
try:
print(text, "->", int(text))
except ValueError as error:
print(text, "->", error)
try:
print("1" + 1)
except TypeError as error:
print("TypeError:", error)
3.5
3 -3
43 5.0
7 days
False True False True
False
42 -> 42
3.5 -> invalid literal for int() with base 10: '3.5'
4 2 -> invalid literal for int() with base 10: '4 2'
TypeError: can only concatenate str (not "int") to str
- Verdict: native. In mixed arithmetic Python widens
inttofloatandfloattocomplex. It never converts betweenstrand a number on its own. int(x)truncates a float toward zero. On a string it parses, accepts white space around the digits, and raisesValueErrorfor any other text.bool(x)is the conversion thatifuses. Empty strings and empty containers are false, so"0"and[0]are true.- A float has 53 bits of significand, so
float(2**53 + 1)is not equal to the integer.
#include <print>
#include <stdexcept>
#include <string>
#include <typeinfo>
struct Shape {
virtual ~Shape() = default;
};
struct Circle : Shape {
double radius = 2.0;
};
struct Square : Shape {};
int main() {
double d = 3.99;
int i = static_cast<int>(d);
long wide{i};
std::println("{} {}", i, wide);
Circle circle;
Shape& shape = circle;
if (auto* c = dynamic_cast<Circle*>(&shape)) {
std::println("circle {}", c->radius);
}
std::println("square? {}", dynamic_cast<Square*>(&shape) != nullptr);
try {
[[maybe_unused]] Square& s = dynamic_cast<Square&>(shape);
} catch (const std::bad_cast&) {
std::println("bad_cast");
}
std::println("{}", std::stoi("42") + 1);
try {
std::stoi("abc");
} catch (const std::invalid_argument&) {
std::println("invalid_argument");
}
}
3 3
circle 2
square? false
bad_cast
43
invalid_argument
- Verdict: native. C++ has the implicit conversions of C, plus four named casts:
static_cast,dynamic_cast,const_castandreinterpret_cast. dynamic_castchecks a downcast at run time. A failed pointer cast givesnullptr, and a failed reference cast throwsstd::bad_cast.- Braces reject a narrowing conversion, so
long wide{i}compiles butint n{3.99}does not (see Pitfalls on the concept page). std::stoiparses text and throwsstd::invalid_argumentwhen no conversion is possible.
public class Main {
public static void main(String[] args) {
int code = 'A' + 1;
long wide = code;
double half = 7 / 2;
System.out.println(code + " " + wide + " " + half + " " + 7 / 2.0);
System.out.println((int) 3.99 + " " + (int) -3.99);
System.out.println((byte) 200 + " " + (short) 70000);
System.out.println((int) 3.0e10 + " " + (int) Double.NaN);
System.out.println((float) 16_777_217);
System.out.println(Integer.parseInt("-42") + 1);
Object value = "text";
System.out.println(value instanceof Integer n ? n + 1 : "not an Integer");
}
}
66 66 3.0 3.5
3 -3
-56 4464
2147483647 0
1.6777216E7
-41
not an Integer
- Verdict: native. Widening primitive conversions are implicit. Narrowing conversions need a cast, except for an
intconstant that fits the target. - A narrowing integer cast keeps the low bits, so
(byte) 200is -56. A cast fromdoubletointtruncates toward zero, maps NaN to 0 and saturates a value out of range. 7 / 2is integer division. The conversion todoublehappens after it, sohalfis 3.0.- A cast of a reference is checked at run time and can throw
ClassCastException. Theinstanceofpattern tests and converts in one step.
#include <stdio.h>
int main(void) {
unsigned char a = 200;
unsigned char b = 100;
int sum = a + b;
unsigned char wrapped = (unsigned char)(a + b);
double half = 7 / 2;
int truncated = (int)-3.99;
printf("%d %d %.1f %d\n", sum, wrapped, half, truncated);
printf("%zu %zu\n", sizeof a, sizeof(+a));
return 0;
}
300 44 3.0 -3
1 4
atoi cannot report an error. strtol reports where it stopped and sets errno on overflow, so a caller can reject bad input.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static int parse_int(const char *text, int *out) {
char *end;
errno = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return 0;
}
if (errno == ERANGE || value < INT_MIN || value > INT_MAX) {
return 0;
}
*out = (int)value;
return 1;
}
int main(void) {
const char *inputs[] = {"42", "42abc", "", "99999999999"};
for (int i = 0; i < 4; i++) {
int n;
if (parse_int(inputs[i], &n)) {
printf("\"%s\" -> %d\n", inputs[i], n);
} else {
printf("\"%s\" -> rejected\n", inputs[i]);
}
}
printf("atoi(\"42abc\") = %d\n", atoi("42abc"));
return 0;
}
"42" -> 42
"42abc" -> rejected
"" -> rejected
"99999999999" -> rejected
atoi("42abc") = 42
- Verdict: native. The integer promotions and the usual arithmetic conversions run on every arithmetic operator.
a + bis 300, because bothunsigned charoperands becomeintfirst.sizeof(+a)shows the promoted type: 4 bytes forinton the machine that recorded the output.- A conversion to an unsigned type wraps modulo 2ⁿ, so 300 becomes 44. A conversion of a floating value out of the range of the integer type is undefined behavior.
atoi("42abc")returns 42 and gives no sign that it ignored text.
int i = 300;
long wide = i;
byte low = (byte)i;
double d = -3.99;
Console.WriteLine($"{wide} {low} {(int)d}");
Console.WriteLine(int.Parse("42") + 1);
Console.WriteLine(int.TryParse("42abc", out int n) ? n.ToString() : "rejected");
object o = "text";
Console.WriteLine(o as string ?? "null");
Console.WriteLine(o as Uri == null);
try
{
byte checkedLow = checked((byte)i);
Console.WriteLine(checkedLow);
}
catch (OverflowException)
{
Console.WriteLine("OverflowException");
}
300 44 -3
43
rejected
text
True
OverflowException
- Verdict: native. The implicit numeric conversions never lose magnitude. Every other numeric conversion needs a cast.
- In the default unchecked context,
(byte)300keeps the low 8 bits and gives 44. In acheckedcontext the same cast throwsOverflowException. asreturnsnullwhen a reference conversion fails, and a cast throwsInvalidCastException.int.Parsethrows on bad input.int.TryParsereturnsfalseinstead.
console.log(1 + "2", "3" - 1, "3" * "4");
console.log(Number(""), Number(" 42 "), Number("42abc"));
console.log(parseInt("42abc", 10), parseFloat("2.5kg"));
console.log([] + [], [1, 2] + [3]);
console.log(0 == "", "0" == false, null == 0, null == undefined);
console.log(0 === "", "0" === false, NaN == NaN);
console.log(Boolean("0"), Boolean(""), Boolean([]));
console.log(String(123) + 1, Number(true) + 1);
12 2 12
0 42 NaN
42 2.5
1,23
true true false true
false false false
true false true
1231 2
Mixing a BigInt and a Number in arithmetic is the one case where JavaScript refuses to convert.
This code raises TypeError, on purpose.
const big = 2n ** 64n;
console.log(big + 1);
The fix is an explicit conversion: big + 1n, or Number(big) + 1 if the loss of precision is acceptable.
- Verdict: native. Almost every operator converts its operands.
+concatenates if either operand is a string afterToPrimitive, and the other arithmetic operators convert to numbers. Number(text)rejects the whole string if any part is not numeric, but treats an empty string as 0.parseIntreads a prefix and stops at the first character that is not a digit.- An array converts to a string of its elements joined by commas, so
[1, 2] + [3]is"1,23"and[] + []is the empty string. ==converts by the IsLooselyEqual algorithm, and===never converts.NaNis not equal to itself under either operator.
interface Order {
count: number;
}
function readCount(json: string): number {
const raw: unknown = JSON.parse(json);
if (typeof raw !== "object" || raw === null || !("count" in raw)) {
throw new TypeError("no count");
}
const value = Number(raw.count);
if (!Number.isInteger(value)) {
throw new TypeError(`not an integer: ${String(raw.count)}`);
}
return value;
}
const order = JSON.parse('{"count": "42"}') as Order;
console.log(order.count + 1, typeof order.count);
console.log(readCount('{"count": "42"}') + 1);
try {
readCount('{"count": "4x"}');
} catch (error) {
console.log((error as Error).message);
}
421 string
43
not an integer: 4x
- Verdict: native. At run time TypeScript has the conversions of JavaScript, because the compiler removes the types.
x as Tis a type assertion, not a conversion. It changes what the compiler believes and does nothing at run time. In the first lineorder.countis still the string"42", so+ 1concatenates.- A real conversion is a function such as
NumberorString, followed by a check of the result.
package main
import (
"fmt"
"strconv"
)
func main() {
var small int32 = 300
wide := int64(small)
low := byte(small)
f := 3.99
fmt.Println(wide, low, int(f), int(-f))
n, err := strconv.Atoi("42")
fmt.Println(n+1, err)
_, err = strconv.Atoi("42abc")
fmt.Println(err)
var x any = "text"
if s, ok := x.(string); ok {
fmt.Println("string of length", len(s))
}
_, ok := x.(int)
fmt.Println("int?", ok)
fmt.Println(strconv.Itoa(65), string(rune(65)))
}
300 44 3 -3
43 <nil>
strconv.Atoi: parsing "42abc": invalid syntax
string of length 4
int? false
65 A
- Verdict: native. Go has no implicit conversion between numeric types. Even
int32toint64needsint64(x). - An integer conversion keeps the low bits, so
byte(300)from a variable is 44. A constant that does not fit is a compile error. strconvparses and formats text, and returns an error value.x.(T)is a type assertion on an interface value; the two-value form reports failure instead of a panic.string(rune(65))is"A", a code point, not the digits"65".
fn main() {
let small: i32 = 300;
let wide: i64 = small.into();
let low = small as u8;
let checked = u8::try_from(small);
println!("{wide} {low} {checked:?}");
println!("{} {} {}", 3.99_f64 as i32, -1.0e10_f64 as i32, f64::NAN as i32);
println!("{}", -1_i32 as u32);
println!("{:?}", "42".parse::<i32>());
println!("{:?}", "42abc".parse::<i32>());
}
300 44 Err(TryFromIntError(PosOverflow))
3 -2147483648 0
4294967295
Ok(42)
Err(ParseIntError { kind: InvalidDigit })
- Verdict: native. Rust has no implicit numeric conversion.
asis a cast that never fails,FromandIntoare conversions that cannot fail, andTryFromreturns aResult. 300 as u8keeps the low 8 bits and gives 44.u8::try_from(300)returns an error instead.- A float to integer
ascast rounds toward zero, saturates at the limits of the target type and maps NaN to 0. str::parsereturns aResult, so a caller must handle bad text.
count="7"
echo $((count + 1))
name="abc"
echo $((name + 1))
sum="3 + 4"
echo $((sum * 2))
echo $((010 + 1))
if [[ "10" < "9" ]]; then
echo "as strings, 10 sorts before 9"
fi
if ((10 > 9)); then
echo "as numbers, 10 is greater than 9"
fi
8
1
14
9
as strings, 10 sorts before 9
as numbers, 10 is greater than 9
- Verdict: native. Every value is a string. Arithmetic expansion converts it to an integer when it is used.
- Inside
$(( ))a variable name is evaluated as an arithmetic expression.abcnames an unset variable, soname + 1is 1 and not an error. - The value
"3 + 4"is evaluated as an expression, sosum * 2is 14. A leading 0 makes a constant octal, so010is 8 and010 + 1is 9. [[ a < b ]]compares strings, and(( a < b ))compares numbers.
Variations and related ideas
- Coercion and subtyping. An upcast keeps the same object and changes only its static type. A widening conversion makes a value with a different representation. Both are implicit in many languages, but only the first is subtyping. Subtyping covers the first.
- User-defined conversions. C++ converting constructors and conversion functions, C#
implicitandexplicitoperators, and the RustFromtrait let a type define its own conversions.192630 An implicit user-defined conversion has the same risk as a built-in one. A reader cannot see it at the call. - Boxing. A conversion from a primitive value to an object, such as
inttoIntegerin Java, allocates or reuses an object.47 Generics in Java need it, because a type argument must be a reference type. Type erasure explains why. - Truthiness. A condition converts its value to a boolean. Python and JavaScript have rules for every type, and the rules differ:
[]is false in Python and true in JavaScript.11 Null reference covers the related test for a missing value. - Type assertions. A TypeScript
asor an unchecked Java cast of a generic type changes only what the compiler believes.45 No conversion happens, and an error shows later. - Checked and saturating arithmetic. The same choices that a narrowing conversion makes also apply to an arithmetic result that does not fit. Integer overflow or wraparound covers them.
Pitfalls
Loose equality converts both sides
In JavaScript, == converts its operands before it compares them. A value from a form field is a string, and many strings are loosely equal to 0.
This code runs but gives a wrong answer on purpose.
function isEmptyCart(quantity) {
return quantity == 0;
}
console.log(isEmptyCart(0), isEmptyCart(""), isEmptyCart(" "), isEmptyCart("0"), isEmptyCart([]));
console.log([] == ![]);
true true true true true
true
The empty string and a string of white space convert to 0 under ToNumber.9 The array [] goes through ToPrimitive to "" and then to 0.8 In [] == ![], the right side is false, because every object is true under ToBoolean.11 Then both sides convert to 0. The fix is to convert once, check the result, and compare with ===.
function isEmptyCart(input) {
const quantity = input.trim() === "" ? NaN : Number(input);
if (!Number.isInteger(quantity)) {
return "not a number";
}
return quantity === 0;
}
console.log(isEmptyCart("0"), isEmptyCart(""), isEmptyCart("3"));
true not a number false
The plus operator joins strings
In JavaScript, + concatenates if either operand is a string. The other arithmetic operators convert to numbers.10
This code runs but gives a wrong answer on purpose.
const price = "19.99";
const shipping = 5;
console.log(price + shipping);
console.log(price - 1);
19.995
18.99
The first line prints the text 19.995. The fix is to convert at the edge of the program, where the text comes in: Number(price) + shipping is 24.99. TypeScript does not help here when the type of price is wrong. A value from JSON.parse has the type any, and an assertion to number does not convert it (see the TypeScript example).45
A negative number meets an unsigned number
In C, the usual arithmetic conversions turn a signed operand into an unsigned one when the unsigned type has the same or a higher rank.4 strlen returns a size_t, which is unsigned.
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *name = "Ada";
int offset = -1;
if (offset < strlen(name)) {
printf("offset %d is inside the string\n", offset);
} else {
printf("offset %d is past the end\n", offset);
}
return 0;
}
offset -1 is past the end
The value -1 converts to the largest size_t value, so the test is false.5 The fix is to test the sign first and then compare with an explicit conversion: offset >= 0 && (size_t)offset < strlen(name). GCC and Clang warn about this comparison with -Wsign-compare. Go and Rust reject the comparison, because they have no implicit conversion between signed and unsigned types.22
A narrowing cast keeps the low bits
A cast to a narrower integer type succeeds for every value. It keeps the low bits and gives a wrong value without an error.131725
This code runs but gives a wrong answer on purpose.
fn main() {
let requested: i64 = 300;
let level = requested as u8;
println!("volume level {level}");
}
volume level 44
300 is 0x12C, and the low byte 0x2C is 44. The fix in Rust is TryFrom, which returns an error for a value that does not fit.26
fn main() {
for requested in [200_i64, 300] {
match u8::try_from(requested) {
Ok(level) => println!("volume level {level}"),
Err(error) => println!("{requested}: {error}"),
}
}
}
volume level 200
300: out of range integral type conversion attempted
C# has the same problem in its default unchecked context. A cast from long to int discards the high bits.17
This code runs but gives a wrong answer on purpose.
long bytes = 3_000_000_000;
int size = (int)bytes;
Console.WriteLine(size);
-1294967296
The fix is a checked conversion. Then the cast throws OverflowException at the point of the error, not later.17
This code raises OverflowException, on purpose.
long bytes = 3_000_000_000;
int size = checked((int)bytes);
Console.WriteLine(size);
The languages differ on a float that does not fit an integer type:
| Language | int of a float out of range |
NaN to int |
|---|---|---|
| C, C++ | undefined behavior6 | undefined behavior6 |
| Java | saturates to the minimum or maximum13 | 013 |
| C# | unspecified value, or OverflowException when checked17 |
as out of range17 |
| Go | implementation-dependent21 | implementation-dependent21 |
| Rust | saturates2543 | 025 |
A widening conversion can lose precision
Java calls int to float a widening conversion, and it happens without a cast. A float cannot hold every int, so the result is the nearest float.12
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
int id = 16_777_217;
float key = id;
System.out.println(id + " -> " + (int) key);
}
}
16777217 -> 16777216
The fix is to keep identifiers and counts in an integer type. If a floating type is necessary, double holds every int exactly. C# has the same rule. Its implicit conversions from int to float and from long to double can lose precision.16
A downcast fails at run time
A cast to a subtype compiles, and the check happens when the program runs. In Java, a failed check throws ClassCastException.14
This code raises ClassCastException, on purpose.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Object> values = List.of(1, "2", 3);
int total = 0;
for (Object value : values) {
total += (Integer) value;
}
System.out.println(total);
}
}
The string "2" is not an Integer, and a cast cannot turn it into one. The fix is to test the type and convert each case on its own. A string needs a parse, not a cast.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Object> values = List.of(1, "2", 3);
int total = 0;
for (Object value : values) {
if (value instanceof Integer n) {
total += n;
} else if (value instanceof String s) {
total += Integer.parseInt(s);
}
}
System.out.println(total);
}
}
6
Integer.parseInt can also fail. It throws NumberFormatException when the string does not contain a parsable integer.36
Go needs an explicit conversion
Go does not convert between numeric types implicitly, even when no value can be lost.22
This code does not compile, on purpose.
package main
import "fmt"
func main() {
var count int32 = 3
var total int64 = 10
fmt.Println(total + count)
}
The compiler reports invalid operation: total + count (mismatched types int64 and int32). The fix is total + int64(count). The rule removes the C bugs of implicit conversion, and the price is a conversion at each place where types meet.
Braces reject narrowing in C++
In C++, list-initialization makes a narrowing conversion ill-formed.27
This code does not compile, on purpose.
#include <print>
int main() {
int count{3.5};
std::println("{}", count);
}
The compiler stops at int count{3.5}. The form int count = 3.5; compiles and gives 3. Braces are a way to make the compiler check each initialization. When the truncation is wanted, static_cast<int>(3.5) says so. For a value that is not a constant, GCC gives only a warning by default, so a build that uses -Werror catches both cases.28
A cast is not a parse
A conversion between a number and text is a parse or a format. It is not a cast. Go has a conversion from an integer to a string, and it gives the character with that code point.23
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func main() {
id := 65
label := "item-" + string(rune(id))
fmt.Println(label)
}
item-A
The fix is strconv.Itoa(id), which gives "item-65". In the other direction, strconv.Atoi parses text and returns an error value for bad input.38
In C, atoi need not set errno on an error, and its behavior is undefined if the value does not fit.35 strtol reports where it stopped and sets errno to ERANGE on overflow.34 The C example uses it to reject "42abc". In JavaScript, Number("42abc") is NaN, but parseInt("42abc", 10) is 42, because parseInt stops at the first character that is not a digit.937
Cost
- Integer to integer. A conversion between integer sizes is a sign extension, a zero extension or a truncation of bits.21 Narrowing has no run-time check unless the language or the context adds one, as
checkeddoes in C#.17 - Float to integer. Before Rust 1.45,
rustccompiledx as u8to the LLVM instructionfptoui, which gives a poison value for an out-of-range input. Saturation adds checks. The Rust team wrote that the compiler can often remove them, and added the unsafe methodto_int_uncheckedto skip them.43 - Checked downcasts. A cast to a subtype in Java or C#, and a
dynamic_castin C++, does a type test at run time.141929 Astatic_castto a derived class does no test, so a wrong cast is undefined behavior. - Parsing. A parse reads each character and must report errors. A program should parse once, at its edge, and pass typed values inside.
History
- 1975. The Revised Report on ALGOL 68 defined six coercions: deproceduring, dereferencing, uniting, widening, rowing and voiding. It also defined sorts of syntactic position. In a strong position all six coercions can occur. In a soft position only deproceduring is allowed.42
- 1989. Before C89, C compilers used two rules for promoting
unsigned charandunsigned short: unsigned preserving and value preserving. The C89 committee chose value preserving, although the UNIX C compilers had moved toward unsigned preserving. The Rationale calls this the most serious semantic change that the committee made to widespread practice.41 - 1997. The first edition of ECMAScript had only
==and!=, defined by the abstract equality comparison algorithm.39 - 1999. The third edition of ECMAScript added
===and!==, with a strict equality comparison that does not convert.40 - 2011. C++11 made a narrowing conversion inside braces ill-formed. GCC diagnoses it by default for C++11 and later.28
- 2020. Rust 1.45.0, released on 16 July 2020, made
asfrom a float to an integer saturating. Before, an out-of-range cast was undefined behavior, although it needed nounsafeblock. The issue about it was opened in October 2013.43
References
- The Python Standard Library, Built-in Types, Numeric Types, int, float, complex (mixed arithmetic widens the narrower operand)
- The Python Standard Library, Built-in Functions, int (truncation toward zero for floats, and the accepted string form)
- ISO/IEC 9899:201x Committee Draft N1570 (C11), 6.3.1.1 Boolean, characters, and integers, paragraphs 2 and 3 (the integer promotions)
- ISO/IEC 9899:201x Committee Draft N1570 (C11), 6.3.1.8 Usual arithmetic conversions, paragraph 1
- ISO/IEC 9899:201x Committee Draft N1570 (C11), 6.3.1.3 Signed and unsigned integers, paragraphs 1 to 3
- ISO/IEC 9899:201x Committee Draft N1570 (C11), 6.3.1.4 Real floating and integer, paragraph 1
- ECMA-262, ECMAScript 2026 Language Specification, 7.2.13 IsLooselyEqual
- ECMA-262, ECMAScript 2026 Language Specification, 7.1.1 ToPrimitive and 7.1.1.1 OrdinaryToPrimitive
- ECMA-262, ECMAScript 2026 Language Specification, 7.1.4.1.1 StringToNumber and 7.1.4.1.2 StringNumericValue (white space alone gives +0)
- ECMA-262, ECMAScript 2026 Language Specification, 13.15.3 ApplyStringOrNumericBinaryOperator
- ECMA-262, ECMAScript 2026 Language Specification, 7.1.2 ToBoolean
- The Java Language Specification, Java SE 25 Edition, 5.1.2 Widening Primitive Conversion
- The Java Language Specification, Java SE 25 Edition, 5.1.3 Narrowing Primitive Conversion
- The Java Language Specification, Java SE 25 Edition, 5.5 Casting Contexts (checked casts and ClassCastException)
- The Java Language Specification, Java SE 25 Edition, 5.2 Assignment Contexts (narrowing of a constant expression)
- Built-in numeric conversions (C# reference), Implicit numeric conversions (the note on loss of precision)
- Built-in numeric conversions (C# reference), Explicit numeric conversions (integral truncation, and double or float to an integral type)
- The checked and unchecked statements (C# reference), Default overflow-checking context
- Casting and type conversions (C# Programming Guide), Type conversion exceptions at run time (InvalidCastException)
- Type-testing operators and cast expressions (C# reference), The as operator
- The Go Programming Language Specification, Conversions, the subsection Conversions between numeric types
- The Go Programming Language Specification, Numeric types (explicit conversions are required when numeric types are mixed)
- The Go Programming Language Specification, Conversions to and from a string type (an integer converts to a UTF-8 code point)
- The Go Programming Language Specification, Type assertions
- The Rust Reference, Operator expressions, Type cast expressions, numeric casts (r-expr.as.numeric.int-truncation and r-expr.as.numeric.float-as-int)
- Rust standard library, Trait std::convert::TryFrom, the description (no From conversion from i64 to i32) and the stability version 1.34.0
- Working Draft, Programming Languages C++, [dcl.init.list] paragraph 7 (definition of a narrowing conversion) and paragraph 3 (the program is ill-formed)
- Using the GNU Compiler Collection, Options Controlling C++ Dialect, -Wno-narrowing (C++ and Objective-C++ only)
- Working Draft, Programming Languages C++, [expr.dynamic.cast] paragraph 10 (a failed cast gives a null pointer or throws std::bad_cast)
- Working Draft, Programming Languages C++, [expr.cast] paragraph 4 (the casts that the cast notation tries, in order)
- Kotlin documentation, Numbers, Type conversion, and Mixed numeric expressions
- Kotlin documentation, Type checks and casts, as and as? cast operators
- about_Type_Conversion (PowerShell), Operator conversions (the left operand usually decides the type)
- ISO/IEC 9899:201x Committee Draft N1570 (C11), 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions, paragraphs 7 and 8
- ISO/IEC 9899:201x Committee Draft N1570 (C11), 7.22.1 paragraph 1 and 7.22.1.2 The atoi, atol, and atoll functions
- Java SE 25 API, Class Integer, parseInt(String) (throws NumberFormatException)
- ECMA-262, ECMAScript 2026 Language Specification, 19.2.5 parseInt ( string, radix )
- Go standard library, package strconv, ParseInt (ErrSyntax and ErrRange) and Atoi
- ECMA-262, ECMAScript, 1st edition, June 1997, 11.9 Equality Operators and 11.9.3 The Abstract Equality Comparison Algorithm
- ECMA-262, ECMAScript Language Specification, 3rd edition, December 1999, 11.9.4 The Strict Equals Operator ( === ) and 11.9.6 The Strict Equality Comparison Algorithm
- Rationale for International Standard, Programming Languages, C, Revision 5.10, 6.3.1.1 Booleans, characters, and integers (unsigned preserving and value preserving), pages 43 and 44
- A. van Wijngaarden, B. J. Mailloux, J. E. L. Peck, C. H. A. Koster, M. Sintzoff, C. H. Lindsey, L. G. L. T. Meertens and R. G. Fisker, Revised report on the algorithmic language ALGOL 68, Acta Informatica 5, 1975, 6 Coercion (the six coercions and the sorts of syntactic position)
- Announcing Rust 1.45.0, The Rust Blog, 16 July 2020, Fixing unsoundness in casts
- Bash Reference Manual, 6.5 Shell Arithmetic (variables as operands, a null or unset variable is 0, a leading 0 means octal)
- The TypeScript Handbook, Everyday Types, Type Assertions (no run-time check)
- The Go Programming Language Specification, Operators (an untyped constant converts to the type of the other operand)
- The Java Language Specification, Java SE 25 Edition, 5.1.7 Boxing Conversion
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag E7JK4A Edit this page History Report an error Markdown