Home  >  Article  >  Backend Development  >  What are implicit type conversions and explicit type conversions in C language?

What are implicit type conversions and explicit type conversions in C language?

PHPz
PHPzforward
2023-09-08 22:13:011062browse

Converting one data type to another is called type conversion.

  • Implicit type conversion
  • Explicit type conversion
  • ul>

    Implicit type conversion

    • When operating When numbers have different data types, the compiler provides implicit type conversion.

    • It is done automatically by the compiler by converting smaller data types to larger data types.

    int i,x;
    float f;
    double d;
    long int l;

    What are implicit type conversions and explicit type conversions in C language?

    Here, the above expression finally evaluates to a "double" value.

    Example

    The following is an example of implicit type conversion -

    int x;
    for(x=97; x<=122; x++){
       printf("%c", x); /*Implicit casting from int to char %c*/
    }

    Explicit type conversion

    • Explicit type conversion by User completion using the (type) operator.

    • Before performing the conversion, a runtime check is made to see if the target type can hold the source value.

    int a,c;
    float b;
    c = (int) a + b

    Here, the result of 'a b' is explicitly converted to 'int' and then assigned to 'c'.

    Example

    The following is an example conversion of explicit type-

    int x;
    for(x=97; x<=122; x++){
       printf("%c", (char)x); /*Explicit casting from int to char*/
    }

    Let us understand the difference between two type conversions through an example-

    Example (Implicit conversion)

    Real-time demonstration

    #include<stdio.h>
    main(){
       int i=40;
       float a;
       //Implicit conversion
       a=i;
       printf("implicit value:%f</p><p>",a);
    }

    Output

    Implicit value:40.000000

    Example (explicit conversion)

    Real-time demonstration

    #include<stdio.h>
    main(){
       int i=40;
       short a;
       //Explicit conversion
       a=(short)i;
       printf("explicit value:%d</p><p>",a);
    }

    Output

    Explicit value:40

The above is the detailed content of What are implicit type conversions and explicit type conversions in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete