C Type Casting
-- Learning is not just about technology, but also about dreams!
- Home
- HTML
- JavaScript
- CSS
- Vue
- React
- Python3
- Java
- C
- C++
- C#
- AI
- Go
- SQL
- Linux
- VS Code
- Bootstrap
- Git
- Local Bookmarks
C Tutorial
C Language TutorialC IntroductionC Environment SetupC VScodeC Program StructureC Basic SyntaxC Data TypesC VariablesC ConstantsC Storage ClassesC OperatorsC Decision MakingC LoopsC FunctionsC Scope RulesC ArraysC Enum (Enum)C PointersC Function Pointers and Callback FunctionsC StringsC StructuresC UnionsC Bit FieldsC typedefC Input & OutputC File I/OC PreprocessorsC Header FilesC Type CastingC Error HandlingC RecursionC Variable ArgumentsC Memory ManagementC Undefined BehaviorC Command Line ArgumentsC Safe FunctionsC Sorting AlgorithmsC Project StructureC Language ExamplesC Language Classic 100 ExamplesC Quiz
C Standard Library
C Standard Library β Reference Manual<a href="#" title="C Standard Library β ">C Standard Library β <a href="#" title="C Standard Library β ">C Standard Library β <a href="#" title="C Standard Library β ">C Standard Library β <a href="#" title="C Standard Library β ">C Standard Library β <a href="#" title="C Standard Library β ">C Standard Library β <a href="#" title="C Standard Library β ">C Standard Library β <a href="#" title="C Standard Library β
C Type Casting
Type casting is converting a variable from one type to another data type. For example, if you want to store a long value into a simple integer, you need to cast the long type to an int type. You can use the cast operator to explicitly convert a value from one type to another, as shown below:
(type_name) expression
Look at the following example, which uses the cast operator to divide one integer variable by another integer variable, resulting in a floating-point number:
Example
#include<stdio.h>
int main()
{
int sum = 17, count = 5;
double mean;
mean = (double)sum / count;
printf("Value of mean : %fn", mean );
}
When the above code is compiled and executed, it produces the following result:
Value of mean : 3.400000
Here it should be noted that the cast operator has a higher precedence than division, so the value of sum is first converted to double, and then divided by count, yielding a value of type double.
Type conversion can be implicit, automatically performed by the compiler, or explicit, specified using the cast operator. It is a good programming practice to use the cast operator whenever type conversion is needed.
Integer Promotion
Integer promotion is the process of converting integer types smaller than int or unsigned int to int or unsigned int. Look at the following example, which adds a character to an integer:
Example
#include<stdio.h>
int main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %dn", sum);
}
When the above code is compiled and executed, it produces the following result:
Value of sum : 116
Here, the value of sum is 116 because the compiler performs integer promotion, converting the value of 'c' to its corresponding ASCII value before performing the actual addition operation.
Usual Arithmetic Conversion
The usual arithmetic conversion implicitly converts values to a common type. The compiler first performs integer promotion; if the operands have different types, they are converted to the highest type in the following hierarchy:
The usual arithmetic conversion does not apply to the assignment operators, logical operators && and ||. Let us look at the following example to understand this concept:
Example
#include<stdio.h>
int main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %fn", sum );
}
When the above code is compiled and executed, it produces the following result:
Value of sum : 116.000000
Here, c is first converted to an integer, but since the final value is of type float, the usual arithmetic conversion applies, and the compiler converts i and c to floating-point, then adds them to produce a floating-point number.
3 Notes Write a Note
-
#0 sweet bamboo shoots
102***1933@qq.com 162 If the operands on both sides of an operator are of different types, they must first be converted to the same type. The lower type is converted to a higher type before the operation. The conversion rules are shown in the figure below.
sweet bamboo shootssweet bamboo shoots
102***1933@qq.com 9 years ago (2017-09-08)
-
#0 xxxxripxxxx
roc***lyman@163.com 305 In C,
printfcan use the%fplaceholder for bothdoubleandfloatoutput, and they can be used interchangeably. Additionally,doublecan also use%lf.However, for
scanfinput,doublemust use%lf, andfloatmust use%f; they cannot be mixed.xxxxripxxxxxxxxripxxxx
roc***lyman@163.com 7 years ago (2020-01-10)
-
#0 ssl
157***1786@qq.com 53 To improve efficiency, C language will directly convert two different types to the higher type for calculation.
For example, for variables a and b defined and assigned values of type double and int respectively:
Assuming an
a + boperation is performed, thenbwill be directly implicitly converted to double type before the operation. It should not be understood as a layer-by-layer conversion (i.e., not thatbis first converted tounsigned int, then tolong => unsigned long => long long => unsigned long long => float => double, and finally the operation is performed).p.s: Speaking of operations, for char and short types, they will be implicitly converted to int during operations. Look at the code:
#include <stdio.h> int main() { char c = 22, ch = 33; short m = 23, n = 32; printf("%dn", sizeof(c + ch)); //char and char type operation printf("%dn", sizeof(m + n)); //short and short type operation printf("%d", sizeof(m + ch)); //short and char type operation return 0; }Output:
4 4 4This wasn't covered here, so let me supplement the conversion rules:
1. Assigning float, double, long double to integer types: truncates the decimal part
As in:
#include <stdio.h> int main() { float a = 3.8; int b = a; //Performs an implicit type conversion printf("a=%.2f; b=%d", a, b); return 0; }Based on the conversion rules and implicit type conversion rules, the output is:
a=3.80; b=32. Assigning integer types to floating-point types (float, double, long double): pads with the required number of decimal places
Modifying the above code:
#include <stdio.h> int main() { int a = 8; float b = a; //Performs an implicit type conversion printf("a=%d; b=%f", a, b); return 0; }Output:
a=8; b=8.000000 //%f defaults to outputting 6 decimal places3. Assigning a shorter type to a longer type: pads the required bits, with other bits padded with 0
Assume the following definitions:
char c = 56; short num = 67; int m; long long int n;If the following operations are performed:
m = ((int)c); n = ((long long)nu
YouTip