Converting one datatype into another is known as type-casting or type conversion. There are two types of typecast supported by C:
In Implicit type casting a.k.a. automatic type conversion, the compiler automatically converts the data type when required. This is done to avoid loss of data during certain arithematic operations. However, the conversion may result in loss of the sign when converted from signed datatype to unsigned. The implicit type conversion follows the order provided below.
bool -> char -> short int -> int ->unsigned int -> long ->
unsigned -> long long -> float -> double -> long double
#include<stdio.h>
int main(void)
{
int key = 3;
char str[50];
char ostr[50];
int i = 0;
printf("Insert plain Text\n");
scanf("%s",&str);
while(str[i] != '\0')
{
//Implicit type conversion
ostr[i] = str[i] + key;
i++;
}
ostr[i] = '\0';
printf("Encrypted Text\n");
printf("%s\n",ostr);
return 0;
}
Insert plain Text
ABC
Encrypted Text
DEF
Explicit type conversion is the process of forcefully casting a data type into another.
(type) expression
#include<stdio.h>
int main(void)
{
int x = 5;
int y = 2;
float z;
//Explicit type conversion from int to float
z = (float)x / (float)y;
printf("Explicit Type Conversion: %d / %d = %f\n",x,y,z);
z = x / y;
printf("Without Type Conversion: %d / %d = %f\n",x,y,z);
return 0;
}
Explicit Type Conversion: 5 / 2 = 2.500000
Without Type Conversion: 5 / 2 = 2.000000
C Programming
Overview Hello World Installation Comments Header Files Data Types Tokens Operators Input/Output Format Specifiers Decision Control Loops Type Qualifiers Storage class specifier Arrays Enums Structures Unions Functions Recursions Inline Functions Pointers Pointer Arithematic Call by value and call by reference Linked Lists Passing of Arrays in Functions Preprocessor and Macros Mathematical Operations String Operations Bit Fields Command Line Arguments Variable Arguments Error Handling Type Casting Typedef File Handling Multi Processing Threads Outdated C Programming Memory Management Compilation C Programs Interview Questions MiscellaneousTrending
C Programming
Remember to follow community guidelines and don't go off topic.