Type Implicit Conversions - C Data Type

C examples for Data Type:Type Cast

Introduction

An implicit conversion is performed automatically by the compiler.

For example, any conversions between the primitive data types can be done implicitly.

Demo Code


#include <stdio.h>
int main(void) {
    long l = 5;   /* int -> long */
    double d = l; /* long -> double */
    //from  www .  ja v  a 2 s . co m
    printf("%f",d);
}

Result

The implicit conversions can happen in an expression.

When types of different sizes are involved, the result will be of the larger type.

Demo Code


#include <stdio.h>
int main(void) {

   double d = 5 + 2.5; /* int -> double */

   printf("%f",d);
}

Result

Implicit conversions of primitive types can be further grouped into two kinds: promotion and demotion.

  • Promotion occurs when an expression gets implicitly converted into a larger type
  • Demotion occurs when converting an expression to a smaller type.

Demo Code

#include <stdio.h>
int main(void) {


    /* Promotion */
    long l = 5;   /* int promoted to long */
    double d = l; /* long promoted to double */
    //from   ww w .ja  v  a  2  s .  com
    /* Demotion */
    int i = 10.5; /* warning: possible loss of data */
    char c = i;   /* warning: possible loss of data */

    printf("%c",c);
    printf("%d",i);
}

Result

A demotion conversions generate a warning since the result may lose information.

We can use the explicit cast to remove the warning.


Related Tutorials