Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Cast operator (type)

A cast explicitly converts an expression's value. Its placement determines whether conversion happens before or after a calculation.

Version: C23; repository compiler flag, production runtime not attested

Syntax

(type-name) expression

(type) expression explicitly converts a value; type denotes a type name. Casting neither changes a variable's declared type nor yields an lvalue, so its result cannot be an assignment target.

Except for (void), operand and destination must be scalar, with additional conversion restrictions. (void)expression discards the value while preserving side effects.

(double)a / b performs floating-point division; (double)(a / b) converts an already truncated integer quotient. Conversion of a finite floating-point value to int discards the fractional part by truncating toward zero. If the integral part is outside the range of int, the C23 core language leaves the behavior undefined for a standard floating type. When C23's Annex F binding applies, however, such a conversion from a standard floating type raises the invalid floating-point exception and yields an unspecified result. For a decimal floating type, the C23 core language also requires that exception to be raised in this case and leaves the result unspecified.

Examples

#include <stdio.h>

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

    printf("%.1f\n", (double)a / b);
    printf("%.1f\n", (double)(a / b));
    printf("%d\n", (int)-3.75);
    return 0;
}

Result

3.5
3.0
-3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources