Type Casting And Conversion In C Programming Language.

Type Casting And Conversion In C Programming Language.


Hello Programmer,

Today we will discuss one more most important and useful topic and name of that topic is typecasting and conversion in c language.

when you write any program in c language some time you need to typecast and conversion of one data type to another data type so today we will discuss this topic.


Type Casting:


Typecasting is a process of converting the value of a variable from one type to another and whenever you do casting it does not change the actual value of the variable.

Whenever you use casting one thing must remember that before and the operation takes place both the operands must have the same type. C language converts one or both the operands to the appropriate data types by "Type conversion".


Type Conversion:


Type conversion is the process of converting one predefined data type into another data type.

In c language, there are 3 types of conversion:

1) Implicit Type Conversion:


Implicit type conversion is that type of conversion which convert lower type variable value into a higher type(which holds a higher range of values or has high precision).

The implicit type conversion is also known as "promotion". If a "char" is converted into "init", it is called internal promotion.

Example:


int I;
char C;
C='A';
I=C;

In this example, the int variable holds the ASCII code of the char 'A'.

  • Whenever you perform an operation between an integer and integer you get an integer result.
  • Whenever you perform an operation between a real and real you get a real result.
  • Whenever you perform an operation between a real and an integer you get real result.


2) Assignment Type Conversion:


Assignment type conversion is used when you assign any value from one type to another type. If the two operands in an assignment operation are of different type then that time the right side operand is automatically converted to the type of the left side.



3) Explicit Type Conversion:


Explicit type conversion is used to convert a type forcibly in a way that is different from the automatic type conversion then explicit type conversion is necessary.

Let's take an example when you divide the total age by the number of persons and you declared total age and the number of a person in an integer that time might be the decimal part of the result of division will be lost and the ratio would represent a wrong figure. This problem can be solved when you convert one of the variables to the floating-point.

e.g. ratio=(float) total_age/no_of_persons;


Example: 

float ratio=34.5;
int Ratio=(int)ratio; /* Explicit casting from float to int. The value of                                      Ratio is 34.*/



Sharing Is Caring...
            

Comments :

Post a Comment