SyntaxStudy
Sign Up
C Type Conversions and Casting
C Beginner 1 min read

Type Conversions and Casting

C performs implicit type conversions in expressions that mix different types. The general rule is that the "smaller" type is promoted to the "larger" type before the operation is performed. For example, adding an `int` and a `double` converts the `int` to `double` first. These promotions are called the usual arithmetic conversions, and understanding them prevents subtle bugs like accidental integer division. An explicit cast lets you force a conversion that the compiler would not do implicitly, or that would otherwise generate a warning. The syntax is `(type) expression`. Casts should be used sparingly and intentionally; a cast that silences a warning without fixing the underlying issue can hide real bugs. Common safe uses include converting between numeric types when you know the range is safe, and converting pointer types in well-defined ways. Integer overflow is undefined behaviour for signed types but well-defined (wraps around) for unsigned types. Mixing signed and unsigned values in comparisons is a frequent source of bugs — a negative `int` compared with an unsigned value can produce surprising results because the signed value is implicitly converted to unsigned. Always check compiler warnings for sign-comparison issues.
Example
#include <stdio.h>

int main(void)
{
    int   a = 7;
    int   b = 2;
    double result;

    /* Integer division — truncates toward zero */
    printf("7 / 2 (int)    = %d\n", a / b);       /* 3 */

    /* Implicit promotion: int -> double */
    result = a / (double)b;
    printf("7 / 2.0        = %.1f\n", result);    /* 3.5 */

    /* Explicit cast to avoid truncation */
    result = (double)a / b;
    printf("(double)7 / 2  = %.1f\n", result);    /* 3.5 */

    /* Dangerous signed/unsigned comparison */
    int    neg  = -1;
    unsigned int pos = 1;
    if ((unsigned int)neg > pos) {
        /* This branch IS taken — -1 becomes a huge unsigned value */
        printf("Signed/unsigned trap: -1 > 1 as unsigned\n");
    }

    /* Safe truncation via explicit cast */
    double pi   = 3.14159;
    int    trunc = (int)pi;
    printf("(int)3.14159   = %d\n", trunc);        /* 3 */

    return 0;
}