Friday, July 29, 2016

C Basics - Type Casting in C

Explicit Conversion:
Type casting is a way to convert a variable from one data type to another data type. You can convert the values from one type to another explicitly using the cast operator as follows.

(type_name) expression

Consider the following example,
#include <stdio.h>
int main() {
   int sum = 17, count = 5;
   double mean;

   mean = sum / count;
   printf("Before Type Cast - Value of mean : %f\n", mean );
   mean = (double)sum / count;
   printf("After Type Cast - Value of mean : %f\n", mean );
   return 0;
The output of the above program would be,
Before Type Cast - Value of mean : 3.000000
After Type Cast - Value of mean : 3.400000

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.

Implicit Conversion:
Integer Promotion:
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Consider the following example,

#include <stdio.h>

main() {

   int  i = 17;
   char c = 'c'; /* ascii value is 99 */
   int sum;

   sum = i + c;
   printf("Value of sum : %d\n", sum );

The output of the above program would be,
Value of sum : 116

Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of 'c' to ASCII before performing the actual addition operation.

Usual Arithmetic Conversion:
The usual arithmetic conversions are implicitly performed by the compiler. The compiler first performs integer promotion; if the operands still have different types, then they are converted to the type that appears highest in the following hierarchy.

long double
unsigned long long
long long
unsigned long
unsigned int

Related topics:
Standard Input-Output in C   |   File Handling in C   |   Preprocessors in C   |   Header Files in C   |   Error Handling in C

List of topics: C Programming

No comments:

Post a Comment