Implicit type Conversion in C | Automatic type conversion in C
It is the predefined method of C due to which, the output of an arithmetic expression is converted into a particular data type. Rule says that output of expression will be of data type having highest number of bytes and range.
For example In an arithmetic expression if one operand is of int type and other of float type, the output will be of float type because float has larger range of values compared to int .
Rules of implicit conversion are:
operand1 | operand2 | Output |
short | short | short |
short | int | int |
short | long | long |
short | float | float |
short | double | double |
short | long double | long double |
short | char | short |
int | int | int |
int | long | long |
int | float | float |
int | double | double |
int | long double | long double |
int | char | int |
long | long | long |
long | float | float |
long | double | double |
long | long double | long double |
long | char | long |
float | float | float |
float | double | double |
float | long double | long double |
float | char | float |
double | double | double |
double | long double | long double |
double | char | double |
long double | long double | long double |
long double | char | long double |
char | char | char |
Program to demonstrate implicit conversion in C Language. |
#include<stdio.h> int main() { int a,b,c; float d, e; a=11; b=4; c=a/b; /*Line 1*/ printf(“\nc=%d”,c); d=a/b; /*Line 2*/ printf(“\nd=%f”,d); e=a/d; /*Line 3*/ printf(“\ne=%f”,e); c=a/d; /*Line 4*/ printf(“\nc=%d”,c); return(0); } |
Output: |
c=2 d=2.000000 e=2.75 c=2 |
Description |
** In line 1, a and b are int variable so result of a/b is of int type i.e. 2. so c contains 2.
In line 2, a and b are int type variables so result of a/b is of int type i.e. 2. but it is assigned to float variable d. So d will contain 2.000000. In line 3, a is int and d is float type variable so result of a/b is of float type i.e. 2.75. It is assigned to float variable e. So e will contain 2.75. In line 4, a is int and d is float type variable. Result of a/b is of float type i.e. 2.75. it is assigned to int variable c So c will contain 2 only ignoring digits after decimal point. |