Fact-checked by Grok 2 weeks ago

Type conversion

Type conversion, also known as type casting or type coercion, refers to the process in of changing a value from one to another, such as from an to a floating-point number, to enable compatibility in expressions, assignments, or operations across different s. This mechanism is fundamental in statically and dynamically typed programming languages, where it allows values to be used in contexts requiring a specific type, often involving runtime or compile-time adjustments to the underlying representation of data. Type conversions can be implicit, performed automatically by the or interpreter without explicit intervention, or explicit, where the specifies the desired transformation to ensure precision and avoid unintended behaviors. Implicit conversions, sometimes called coercions, occur when the language rules promote or widen a value to a compatible type, such as converting an to a in operations to preserve accuracy, but they may lead to subtle errors if not managed carefully. In contrast, explicit conversions require direct syntax, like in C++ using static_cast<float>(value) or in using (float)value, providing greater control and often including checks for potential data loss during narrowing operations, such as truncating a to an . These distinctions are crucial in languages with strong typing systems, where conversions enforce while balancing performance and expressiveness. In practice, type appears across major programming languages with language-specific rules: , implicit promotions follow conversion ranks during operations, potentially causing overflow if ranks are mismatched; supports flexible conversions via built-in functions like int() or str(), accommodating its dynamic typing; and in C#, the [Common Language Runtime](/page/Common Language Runtime) handles both built-in and user-defined conversions, with explicit casts risking exceptions for incompatible types. Such mechanisms are implemented during compilation or interpretation, where compilers insert code to adjust bit representations, ensuring semantic correctness but sometimes introducing overhead. Despite their utility, type conversions carry risks, including loss of precision in narrowing cases (e.g., decimal truncation), unexpected runtime errors from invalid casts, and security vulnerabilities if unchecked conversions allow buffer overflows in low-level languages like C. Best practices emphasize explicit conversions for clarity, thorough testing of edge cases, and leveraging language features like safe casting operators to mitigate these issues, thereby maintaining program reliability and performance.

Core Concepts

Definition and Purpose

Type conversion, also known as type casting or type coercion, is the process of converting a value from one data type to another, such as changing an to a floating-point number or a to a numeric value. This operation alters the representation of the data to align with the requirements of the target type, potentially involving adjustments in storage format, precision, or range. In programming, it ensures that values can be used appropriately across different contexts within a . The primary purpose of type conversion is to facilitate between disparate data types during operations like arithmetic expressions, function invocations, and data persistence. By enabling such compatibility, it prevents runtime or compile-time type errors that could arise from mismatched operands in mixed-type scenarios. Additionally, type conversion supports essential tasks in algorithms, such as performing calculations on user input or manipulating textual data for . Historically, type conversion originated in early programming languages like during the , where it addressed the need to handle mixed numeric types—such as fixed-point (integer) and floating-point—in expressions. Initial designs in I (1954) permitted mixed-mode arithmetic with automatic type determination based on assignment context, though later refinements in restricted these to promote efficiency and explicit control. The concept evolved alongside in the 1970s, incorporating more rigorous type systems to better manage memory allocation and numerical precision in languages emphasizing modularity and safety. Common examples illustrate its practical role: converting the "123" to the 123 enables operations on textual input, while truncating the floating-point value 3.14 to the 3 allows it to serve as an without fractional complications. These conversions, which may occur implicitly or explicitly depending on the language, underscore the mechanism's foundational importance in seamless program execution.

Implicit versus Explicit Conversion

Type conversion in programming languages is broadly classified into implicit and explicit forms, each serving distinct roles in managing compatibility during operations. Implicit conversion, also known as , occurs automatically when the or interpreter changes a value's type to match the context of an operation, without requiring programmer intervention. This mechanism prioritizes convenience by enabling seamless interactions between compatible types, particularly in widening conversions where no is possible, such as promoting an to a floating-point number in arithmetic expressions. However, implicit conversions can introduce risks in narrowing scenarios, where information may be lost or misinterpreted, potentially leading to subtle errors or vulnerabilities if not carefully managed. For instance, adding an value of 5 to a floating-point value of 3.5 would implicitly promote the integer to float, yielding a result of 8.5 as a floating-point number. In contrast, explicit conversion requires the to deliberately specify the type change using operators or functions, ensuring clear intent and providing control over potentially lossy transformations. This approach is essential when implicit is disallowed by the language's rules or when precision needs to be explicitly handled, such as converting a floating-point value to an . For example, explicitly 3.9 to an would truncate it to 3, discarding the fractional part. The primary differences between implicit and explicit conversions lie in their automation, safety implications, and application scope: implicit conversions emphasize efficiency and safety for compatible, lossless type promotions following hierarchies like to to to , while explicit conversions enforce programmer oversight for incompatible or risky cases, reducing ambiguity but increasing code verbosity. These distinctions tie into broader designs, where widening conversions (e.g., smaller to larger types) are often implicit to avoid unnecessary casts, whereas narrowing requires explicit action to prevent unintended .

Type Systems and Mechanisms

Role in Static and Dynamic Typing

In static typing systems, type conversions are verified and enforced at , allowing the to detect type mismatches early in the development process. For instance, in languages like , implicit conversions are permitted for safe promotions, such as promoting an to a floating-point number, while explicit casts are required for potentially unsafe operations to prevent unintended or . This approach enables early error catching by rejecting incompatible types before runtime, though it imposes stricter rules that can reduce flexibility during code evolution. In dynamic typing systems, type conversions are typically resolved implicitly at , often based on the behavior of the values involved rather than predefined declarations. Languages such as exemplify this by allowing variables to change types dynamically, with conversions handled through built-in functions or , supporting where compatibility is inferred from method availability. While this fosters greater flexibility and rapid prototyping, it increases the risk of runtime errors, such as type mismatches that only surface during execution. Hybrid type systems, like that in , primarily employ static typing for compile-time checks on variables and expressions but incorporate dynamic elements, such as treating collections of objects polymorphically at . This blend allows static verification of most type conversions—implicit for widening and explicit for narrowing—while permitting resolution in generic structures, balancing early detection with adaptability. The role of type conversion in these systems profoundly impacts software reliability and development practices: static typing reduces through rigorous compile-time rules, with studies indicating benefits in error detection, whereas dynamic typing aids prototyping but demands vigilant handling to mitigate type-related failures. Implicit and explicit conversions function as key mechanisms tailored to each paradigm's needs.

Widening and Narrowing Conversions

In programming languages, widening conversions transform a value from a data type with a smaller or to one with a larger or , generally preserving the original value, though conversions from s to floating-point types may lose for large values due to limited mantissa bits in the target type. For instance, converting an value of 5 to a results in 5.0, maintaining exact since the target type can accommodate all values of the source type exactly in this case. These conversions are typically performed implicitly by the or , as they pose minimal risk of . Common examples follow numeric type hierarchies defined in language specifications, such as byte to short, short to , to long, long to , and to , where each step expands the possible value range or bit width. In static typing systems, widening conversions are often allowed without explicit intervention to facilitate arithmetic operations or assignments between compatible types. Narrowing conversions, in contrast, move a value from a larger or more precise type to a smaller or less precise one, potentially leading to , , or loss of fractional parts. For example, converting a value of 3.9 to an yields 3 through of the decimal portion, discarding that the source type supported. These operations usually require explicit programmer intervention, such as , due to the risk of , and in unchecked scenarios, they can result in , particularly for signed integer overflows in languages like C++. String conversions to numeric types, such as "123" to an , involve rather than direct range expansion or contraction but can align with widening principles if the resulting number fits within a broader type; however, invalid inputs often trigger exceptions rather than silent failures. To mitigate risks in narrowing, modern languages provide safe wrappers or checked mechanisms, like 's Integer.parseInt method, which throws a NumberFormatException on overflow or invalid data, promoting reliable error handling over undefined outcomes.

Explicit Conversion Techniques

Casting in C-like Languages

In C-like languages such as C, C++, and Java, implicit type conversions occur automatically during expression evaluation to ensure type compatibility, particularly in arithmetic operations. For instance, when an integer is added to a floating-point number, the integer is promoted to float, resulting in a floating-point computation. These conversions follow the usual arithmetic conversion rules defined in the C standard, which first promote smaller integer types like char or short to int, and then balance the operands to a common type, such as promoting both to double if one is float and the other is int. In Java, similar implicit promotions apply to numeric types in a hierarchy from byte to short, int, long, float, and double, ensuring operations like byte + int yield an int result without explicit intervention. Explicit casting allows programmers to force conversions that would not occur implicitly, using language-specific syntax to control type changes. In C and inherited in C++, the C-style cast (type)expression performs the conversion, such as (int)3.9 truncating to 3 by discarding the fractional part. C++ extends this with safer functional-style casts: static_cast<T>(expr) handles well-defined conversions like numeric widening or pointer-to-base-class upcasts at compile time, while reinterpret_cast<T>(expr) enables low-level bit reinterpretation, such as treating an integer pointer as a void pointer without altering the underlying bits. Java uses explicit casting for narrowing, like (int)3.9f to truncate a float to int, but prohibits unsafe pointer casts since it lacks raw pointers. Pointer casting in C and C++ introduces significant risks due to the lack of runtime checks, potentially leading to undefined behavior. For example, casting a void* to int* assumes the pointed-to memory holds valid integers, but misalignment or invalid access can cause crashes or data corruption. Narrowing conversions without bounds checks, such as (int)(1e9 * 1e9), invoke undefined behavior by overflowing the integer range before truncation, often wrapping around unexpectedly on most platforms. In Java, implicit autoboxing and unboxing handle conversions between primitives and their wrapper classes, like assigning an int to an Integer automatically, but can lead to NullPointerExceptions if unboxing a null wrapper. Widening conversions, such as (double)myInt, are generally safe as they preserve the original value without loss, promoting an to for in calculations. However, even safe casts should be used judiciously to avoid subtle errors, as implicit promotions in mixed-type expressions can unexpectedly alter precision or sign.

Conversions in Ada

Ada's emphasizes strong typing and safety, requiring explicit conversions for most operations between distinct types to prevent unintended data loss or errors. Explicit type conversions are performed using the syntax Target_Type(Source_Value), where the source and target must be closely related, such as numeric types ( to ), derived types, or types with compatible components and indices. These conversions include value conversions, which evaluate the source and produce a new value in the target type, and view conversions for tagged types or parameters, which reinterpret the data without copying. During conversion to a subtype with constraints, Ada performs range checks; if the result falls outside the subtype's bounds, it raises Constraint_Error at runtime. For conversions involving string representations, Ada provides predefined attributes on scalar types. The S'Image(X) attribute, where S is a scalar type and X is a value of type S, returns a String depicting X in a canonical form suitable for output, such as decimal for integers or enumeration literals. Conversely, S'Value(Str) parses a String Str and returns the corresponding value of type S'Base, raising Constraint_Error if the string does not represent a valid literal for S. These attributes enable safe, type-checked conversions between scalars and strings, as in the example:
My_Float : Float := Float'Value("3.14");
This converts the string to a Float, with parsing ensuring it fits within the type's range. Similarly, Integer'Image(42) yields the string " 42". Implicit conversions in Ada are restricted to avoid hidden errors, occurring primarily when matching universal types (like integer literals) to specific types during predefined operations or subtype adjustments, such as aligning array indices. For related types within derivation hierarchies, implicit conversions are not generally allowed; explicit casts are required, but they are always subject to overflow, underflow, and range checks to maintain reliability. In contrast to more permissive languages, Ada's design ensures these checks are enforced, promoting error detection. For low-level needs where must be bypassed, such as interfacing with hardware or foreign languages, Ada offers Unchecked_Conversion from the Ada.Unchecked_Conversion generic package. This function performs a bit-for-bit copy from a source type to a target type, regardless of compatibility, with the result being implementation-defined if the types differ in representation. requires specifying source and target types, as in:
function To_Integer is new Ada.Unchecked_Conversion ([Float](/page/Float), [Integer](/page/Integer));
Use of Unchecked_Conversion is discouraged except in controlled scenarios, as it can produce invalid or erroneous data, and it is marked with pragmas Intrinsic and Pure for optimization. To mitigate risks, the Valid attribute can check scalar results for validity post-conversion. In safety-critical applications, the subset of Ada extends these mechanisms with , allowing proofs that conversions respect ranges and invariants without errors. SPARK tools generate verification conditions for explicit conversions, ensuring type-safe behavior through deductive proofs, as detailed in its proof manual. This approach is particularly valuable for certifying conversions in domains like , where unchecked operations are audited rigorously.

Handling in C# and C++

In C# and C++, type conversions in emphasize safety and runtime checks, particularly for hierarchies and reference types, to prevent errors like invalid casts or . These languages support implicit conversions for safe upcasting from derived to base classes, while requires explicit mechanisms to mitigate risks. C# integrates conversions with its (CLR) for managed code, including for value-to-reference transitions, whereas C++ relies on operators and requires (RTTI) for polymorphic casts. In C#, explicit conversions for non-compatible types, such as strings to integers, utilize the System.Convert class, which provides methods like Convert.ToInt32("123") to handle parsing and culture-specific formatting without direct casting. Implicit conversions occur automatically for numeric types (e.g., int to long) and reference types in inheritance scenarios, such as assigning a derived class instance to a base class variable: Derived d = new Derived(); Base b = d;. Boxing represents an implicit conversion of value types to reference types like object, allocating the value on the heap: for example, int i = 123; object o = i;, which unboxes explicitly via casting: int j = (int)o;. For reference types, the is operator tests type compatibility before casting, returning a boolean (e.g., if (input is Mammal m) { m.Eat(); }), while the as operator performs safe casting, yielding null on failure: Mammal m = animal as Mammal; if (m != null) { m.Speak(); }. Upcasting is implicit and safe in inheritance, treating derived objects as base types without loss, but downcasting from base to derived is explicit and risky, potentially throwing InvalidCastException unless guarded by is or as. C# also supports nullable value types (T?) for optional conversions, with implicit assignment from non-nullable types (e.g., int? n = 10;) and the null-coalescing operator (??) for safe extraction: int value = n ?? -1;, avoiding exceptions on null values. In C++, explicit conversions leverage cast operators tailored to object-oriented contexts, with dynamic_cast enabling polymorphic casts along hierarchies, requiring RTTI and virtual functions in the base . For , Derived* d = dynamic_cast<Derived*>(basePtr); returns nullptr if invalid, ensuring safety: if the pointer is valid, derived-specific methods can be called without . Upcasting remains implicit and compile-time safe for public (e.g., Base* b = derivedPtr;), avoiding overhead, while demands explicit checks to prevent accessing invalid members. The const_cast adjusts cv-qualifiers (const or volatile) for pointers and references, such as removing constness: const int* p = &x; int* q = const_cast<int*>(p);, but modifying originally const objects yields . Template-based safe conversions enhance in generic code, often using static_cast within s for well-defined transformations between related types, like numeric or pointer conversions in hierarchies, without checks: template <typename T> T safeConvert(U u) { return static_cast<T>(u); }. These mechanisms prioritize compile-time verification where possible, with dynamic_cast reserved for polymorphism to balance performance and correctness in scenarios.

Advanced Conversion Methods

Type Assertions in TypeScript and Go

Type assertions in TypeScript and Go provide mechanisms for explicitly treating a value as a specific type at runtime, particularly when dealing with dynamic or interface-based types, though they differ in enforcement and context. In TypeScript, type assertions allow developers to override the type checker by informing the compiler that a value should be treated as a more specific type, which is useful in scenarios where the type system cannot infer the intended type precisely, such as when working with values from JavaScript's dynamic nature. These assertions are purely a compile-time construct and do not generate runtime checks or perform any value conversion, relying on the developer's assurance that the assertion is safe. TypeScript supports two syntaxes for assertions: the angle-bracket form <Type>value or the as keyword with value as Type. For instance, to access the of a treated from an value, one might write (x as [string](/page/String)).length, which tells the to treat x as a without performing any validation. Additionally, the non-null assertion ! can be appended to expressions to assert that a value is not or , such as element!.innerHTML, suppressing optional chaining warnings at . An example of a basic assertion is let num = <number>someValue;, where someValue is treated as a number by the , but no occurs—the underlying value remains unchanged, potentially leading to errors if the assertion is incorrect. These features enhance static-like safety in by narrowing types during development, but they can lead to errors if the assertion is incorrect, as no checks occur in the emitted code. In Go, type assertions are used to extract the underlying type from an value, enabling access to type-specific methods or fields in a language that supports through interfaces but maintains static overall. The syntax is value.(Type), which attempts to assert that the interface value holds a value of type Type; if successful, it returns the concrete value, but if not, it panics at unless handled safely. For example, s := i.(string) extracts a from interface i, potentially causing a if i does not contain a . To avoid panics, Go provides the comma-ok : val, ok := i.(string), where ok is a indicating success, allowing conditional handling like if ok { /* use val */ }. Type assertions often follow type switches, which inspect an interface's type dynamically, such as in a that branches on possible underlying types. This explicit resolution is essential in Go's interface system, where values can be stored without knowing their concrete type at , promoting safe interaction with dynamic elements in a statically typed environment. While both languages use type assertions to bridge gaps between broader and narrower types, TypeScript's approach emphasizes compile-time convenience for JavaScript's flexibility, offering no overhead or enforcement to maintain . In contrast, Go's assertions involve checks by default, aligning with its statically typed but interface-driven design, where explicit assertions ensure during execution and prevent unintended behaviors through panics or the comma-ok pattern. This distinction highlights TypeScript's role in providing developer ergonomics atop a dynamic , versus Go's focus on robust, checked conversions in a compiled, systems-oriented language.

Implicit Casting via Untagged Unions

Untagged unions provide a mechanism for implicit type conversion in low-level languages like C, where multiple data types share the same memory space without any runtime discriminator to identify the active variant. This allows flexible reinterpretation of data through type punning, where the bit representation of one type is accessed as another, facilitating efficient storage and conversion without explicit casting operators. In C, untagged unions are defined as structures with overlapping members, such as union Example { int i; float f; char str[4]; };, where the union's size matches the largest member to accommodate any of them. Per the C99 standard, the value of a union member other than the last stored into has an unspecified value, though implementations typically reinterpret the bit pattern of the stored value when accessing another member, enabling type punning by treating the shared bytes according to the target type's layout. No runtime tags are used; the compiler tracks the intended active member at compile time, but the language permits punning for optimization or variant handling, such as storing an integer or character array in the same footprint to save space in embedded systems. This approach is particularly suited to low-level programming domains like networking, where unions parse variable-length binary protocols by reinterpreting byte streams as different or types, or in programming, where pixel data might be punned between formats like RGBA integers and individual color channels for processing efficiency. However, risks arise from the lack of : accessing an inactive member can yield garbage values or trap representations if the bit patterns do not align portably across architectures (e.g., due to or ), leading to results in practice despite the standard's defined reinterpretation. Programmers must manually track the active type, often via conventions or comments, to avoid subtle bugs in such code. A representative example illustrates this punning (assuming a little-endian architecture, where results may vary on big-endian systems due to byte order):
c
#include <stdio.h>

union Data {
    int n;
    char c;
};

int main() {
    union Data d;
    d.n = 65;  // Store integer value
    printf("%c\n", d.c);  // Access as char (may output 'A' on little-endian)
    return 0;
}
Here, the integer 65's representation is accessed via the char member, demonstrating the union's role in type reinterpretation without tags, though the exact output depends on the system's endianness.

Practical Implications

Security Vulnerabilities

Unsafe type conversions, particularly narrowing operations, can lead to truncation errors where data is lost during casting from a larger to a smaller type, such as converting an integer to a character, potentially enabling exploits by altering program behavior or causing overflows. For instance, in C and C++, assigning a value larger than the target type's range to a narrower type truncates the higher bits, which may result in incorrect calculations or buffer overflows if the truncated value is used for memory operations. Similarly, string-to-number parsing flaws arise when unvalidated input strings are converted without proper bounds checking, allowing malicious inputs to cause data corruption or unauthorized access. These issues stem from improper input validation during type coercion, where numeric expectations are not enforced. In C-like languages, unchecked casts exacerbate format string vulnerabilities, where user-supplied strings are passed directly to functions like without validation, treating the input as a format specifier and enabling attackers to read or write arbitrary memory locations. This occurs because the does not enforce safe handling of variable arguments, allowing format directives (e.g., %x for hex output) to interpret stack contents maliciously. To mitigate these risks, developers should use safe conversion APIs, such as , which parses strings to long integers while providing error detection via an endptr parameter and return value checks for overflow or invalid input, unlike unsafe functions like atoi. Input validation must precede conversions, ensuring strings match expected formats (e.g., numeric-only for string-to-number) to prevent injection or truncation exploits. Additionally, static analysis tools like can detect type conversion defects by scanning source code for unchecked casts, truncation errors, and improper parsing, identifying potential vulnerabilities before deployment. Historical incidents highlight the severity of these flaws. The 1988 exploited a in the fingerd daemon by sending an oversized string input that overflowed a fixed-size , as the gets() function performed no bounds checking on input length. Similarly, the 2014 vulnerability in stemmed from improper validation of the length field in the heartbeat extension, where a 16-bit length value was trusted without bounds checking before using it in a memcpy operation to a larger , enabling remote attackers to read up to 64KB of server memory per request and exposing sensitive data like private keys.

Performance and Best Practices

Type conversions can significantly impact program performance, particularly in terms of CPU cycles and memory usage, depending on their nature and frequency. Implicit conversions between compatible built-in types, such as promoting an integer to a floating-point for arithmetic operations, are typically inexpensive and often optimized away by the compiler, involving minimal or no additional instructions beyond register adjustments. In contrast, explicit conversions requiring runtime checks, such as C++'s dynamic_cast for polymorphic types, introduce substantial overhead due to type information traversal and validation, with unoptimized implementations showing up to 550% slowdown compared to static alternatives in benchmarked scenarios like LLVM codebases. Narrowing conversions, which risk data truncation, should be minimized to avoid not only precision loss but also indirect costs from embedded conditional logic that may disrupt instruction pipelines. To optimize performance while ensuring safety, developers should prefer widening or implicit conversions when they preserve value integrity, as these leverage the compiler's without runtime expense. Where possible, opt for type-safe alternatives like C++ templates or to eliminate the need for casts entirely, enabling better compile-time optimizations and avoiding overhead. For unavoidable explicit conversions, document their purpose clearly with comments to aid maintenance, and rigorously test edge cases—such as conversions involving maximum or minimum representable values—to catch or underflow issues early. Compiler flags and static tools play a key role in enforcing efficient practices. For instance, GCC's -Wconversion option warns about implicit conversions that may alter values, such as signed-to-unsigned shifts or truncations to smaller types, helping developers identify and refactor costly or risky operations at . Linters integrated into IDEs or build systems can further detect superfluous casts, reducing unnecessary runtime checks. In performance-sensitive contexts, such as loops processing large datasets, batch conversions outside iteration boundaries to amortize costs and boost throughput—for example, converting an of integers to doubles once before vectorized computations. tools like Valgrind's Callgrind extension allow measurement of conversion-induced overhead by simulating instruction execution and behavior, guiding targeted optimizations.

References

  1. [1]
    Type Conversion - an overview | ScienceDirect Topics
    Type conversion is defined as the process of converting a value from one data type to another, such as from integer to floating-point, to enable mixed ...Introduction to Type... · Type Conversion in... · Type Conversion in Compiler...
  2. [2]
    Chapter 5. Conversions and Contexts
    A conversion from type S to type T allows an expression of type S to be treated at compile time as if it had type T instead. In some cases this will require a ...
  3. [3]
    Data Types - UTK-EECS
    Type Conversion: An explicit request by the programmer for the compiler to insert code into the program to convert one type to another, compatible type. For ...
  4. [4]
    11.4. Conversion Operations
    C++ Fundamental Type Conversions​​ For example, the types int and double are different kinds of numbers, and converting them is a meaningful operation. Many ...
  5. [5]
  6. [6]
    Casting and type conversions - C# - Microsoft Learn
    Type conversion exceptions at run time ... In some reference type conversions, the compiler can't determine whether a cast is valid. It's possible for a cast ...
  7. [7]
    Python Type Conversion (With Examples) - Programiz
    In programming, type conversion is the process of converting data of one type to another. For example: converting int data to str .
  8. [8]
    Type Conversion in .NET - Microsoft Learn
    Sep 14, 2021 · Type conversion creates a value in a new type that is equivalent to the value of an old type, but does not necessarily preserve the identity (or exact value) ...
  9. [9]
  10. [10]
    Type conversions and type safety | Microsoft Learn
    Jun 18, 2025 · This document identifies common type conversion problems and describes how you can avoid them in your C++ code.
  11. [11]
    Data Type Conversion - an overview | ScienceDirect Topics
    Data type conversion refers to the process of changing the representation of data from one data type to another. It affects memory usage, execution time, ...
  12. [12]
    Data Type Conversions – Programming Fundamentals - Rebus Press
    Changing a data type of a value is referred to as “type conversion”. There are two ways to do this: ... The value being changed may be: Promotion – going from a ...
  13. [13]
    The history of Fortran I, II, and III - ACM Digital Library
    Although our Preliminary Report had included such expressions, and rules for evaluating them, we felt that if code for type conversion ... A Guide to FORTRAN ...
  14. [14]
    [PDF] Towards a Theory of Type Structure - CIS UPenn
    The type structure of programming languages has been the subject of an active development characterized by continued controversy over basic. (1-7) principles ...
  15. [15]
    Type Checking & Conversion :: CC 410 Textbook
    Aug 10, 2023 · In some languages, we can also perform an implicit cast. This is where the compiler or interpreter changes the type of our value behind the ...
  16. [16]
    INT02-C. Understand integer conversion rules - SEI CERT C Coding Standard - Confluence
    ### Summary of Integer Conversion Rules (SEI CERT C Coding Standard)
  17. [17]
    Chapter 5. Conversions and Contexts
    Kinds of Conversion. Specific type conversions in the Java programming language are divided into 13 categories. 5.1.1. Identity Conversion. A conversion from ...
  18. [18]
    3. Data model
    Summary of each segment:
  19. [19]
    Risky Dynamic Typing-related Practices in Python: An Empirical Study
    The goal of this article is to aid in the understanding of developers' high-risk practices toward dynamic typing and the early detection of type-related bugs.
  20. [20]
    Impact of Using a Static-Type System in Computer Programming
    Additionally, they are predicted to decrease the number of defects in a code due to early error detection. However, only a few empirical experiments exist on ...
  21. [21]
    Always-available static and dynamic feedback - ACM Digital Library
    Whereas dynamic typing enables rapid prototyping and easy experimentation, static typing provides early error detection and better compile time optimization.
  22. [22]
    Type Conversion
    Widening conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another ...
  23. [23]
    [PDF] Concepts of Programming Languages - Lecture 11 - Expressions
    A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g., ...
  24. [24]
    [PDF] Software II: Principles of Programming Languages Why Expressions?
    Type Conversions. • A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., float to.
  25. [25]
    Narrowing and Widening Conversions - Open Standards
    The nearest widening conversion is the one that preserves more possible subsequent conversions. Specifically, given widening conversions A→B, A→C and B→C, but ...
  26. [26]
    Best practices to safely navigate pointers in C/C++ - Embedded
    Aug 20, 2024 · Avoiding Common Pointer Pitfalls. Pitfall #1 – Casting Pointers. In C, casting pointers can hide issues and lead to undefined behavior.
  27. [27]
    Autoboxing and Unboxing - The Java™ Tutorials
    Autoboxing is the automatic conversion of primitive types to their wrapper classes, while unboxing is the reverse conversion of wrapper classes to primitives.
  28. [28]
    Usual Arithmetic Conversions | Microsoft Learn
    Aug 3, 2021 · The conversions performed by C operators depend on the specific operator and the type of the operand or operands.
  29. [29]
    4.6 Type Conversions - Ada Resource Association
    4.6 Type Conversions. 1. Explicit type conversions, both value conversions and view conversions, are allowed between closely related types as defined below.Missing: unchecked_conversion | Show results with:unchecked_conversion
  30. [30]
    Scalar Types
    ### Summary of 'Image and 'Value Attributes for Scalar Types in Ada
  31. [31]
    Unchecked Type Conversions
    ### Summary of Unchecked_Conversion in Ada
  32. [32]
    13.9.2 The Valid Attribute
    The Valid attribute can be used to check the validity of data produced by unchecked conversion, input, interface to foreign languages, and the like. Static ...
  33. [33]
    8. Applying SPARK in Practice - Documentation - AdaCore
    SPARK is a subset of Ada for formal verification, used as a safe coding standard, and can guarantee that programs do not read uninitialized data.
  34. [34]
  35. [35]
    Type Punning, Strict Aliasing, and Optimization
    Jun 11, 2013 · This is the best write-up of the issues surrounding type-punning and the C language's aliasing rules that I have come across. The inescapable ...
  36. [36]
    CWE-197: Numeric Truncation Error (4.18) - MITRE Corporation
    Truncation errors occur when a primitive is cast to a primitive of a smaller size and data is lost in the conversion.
  37. [37]
    Vulnerabilities in C : When integers go bad! - Sticky Bits
    Oct 23, 2014 · The simplest way of performing type narrowing is through truncating the bits to the target type's size, e.g. going from int to short will ...
  38. [38]
    CWE-20: Improper Input Validation (4.18) - MITRE Corporation
    Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting ...
  39. [39]
    SQL Injection Prevention - OWASP Cheat Sheet Series
    This cheat sheet will help you prevent SQL injection flaws in your applications. It will define what SQL injection is, explain where those flaws occur, and ...
  40. [40]
    Format string attack - OWASP Foundation
    The Format String exploit occurs when the submitted data of an input string is evaluated as a command by the application.
  41. [41]
    Uncontrolled format string - Vulnerabilities - Acunetix
    Vulnerabilities occur when user-supplied data are used directly as formatting string input for certain C/C++ functions (e.g. fprintf, printf, sprintf, ...
  42. [42]
    What is prototype pollution? | Web Security Academy - PortSwigger
    Prototype pollution is a JavaScript vulnerability that enables an attacker to add arbitrary properties to global object prototypes.
  43. [43]
    JavaScript prototype pollution - Security - MDN Web Docs
    Oct 17, 2025 · Prototype pollution is a vulnerability where an attacker can add or modify properties on an object's prototype. This means malicious values ...
  44. [44]
    strtol
    strtol converts a string to a long integer, decomposing it into whitespace, an integer subject, and unrecognized characters. It returns the converted value or ...
  45. [45]
    Coverity SAST | Static Application Security Testing by Black Duck
    Coverity delivers accurate, scalable static analysis (SAST) for enterprise code databases. Get a deep, accurate analysis of complex codebases, ...
  46. [46]
    How security flaws work: The buffer overflow - Ars Technica
    Aug 25, 2015 · The Morris worm, the first self-replicating malware that spread across the early Internet in a couple of days in 1988, exploited this function.Missing: int- mismatch
  47. [47]
    Heartbleed Bug - OWASP Foundation
    This serious flaw (CVE-2014-0160) is a missing bounds check before a memcpy() call that uses non-sanitized user input as the length parameter. An attacker can ...Severity · Impact Of The Vulnerability · Defending Against...Missing: size_t casting errors<|control11|><|separator|>
  48. [48]
  49. [49]
    [PDF] Link-Time Optimization of Dynamic Casts in C++ Programs
    This paper proposes a link-time optimization to mitigate performance and size overhead of dynamic casts and RTTI data by replacing costly library calls.
  50. [50]
  51. [51]
  52. [52]
  53. [53]
  54. [54]
  55. [55]