Type conversion is divided into: mandatory type conversion and implicit type conversion
So, how to choose the way of conversion and what issues need to be paid attention to?
Syntax for coercion:
(Type)var_name; (Type)value;
The result of the cast:
1. The target type can accommodate the target value, then the result will remain unchanged;
2. The target type cannot accommodate the target value, then the result will be truncated.
Also, it must be noted that not all casts will succeed.
Example: Observe the code below
#include<stdio.h> struct TS{ int i; int j; }; struct TS ts; intmain() { short s = 0x1122; char c = (char)s; // truncation occurs int d = (int)s; int e = (int) 3.1415; unsigned int p = (unsigned int)&ts; //related to the operating system and compiler //long l = (long)ts; cannot convert a custom type to a primitive type. //ts = (struct TS)l; printf("%x\n", s); printf("%x\n", c); printf("%x\n", d); printf("%x\n", e); printf("%x\n", p); //printf("%x\n", l); printf("%p\n", &ts); return 0; }
The result of compiling and running under linux Gcc is:
delphi@delphi-vm:~/will$ ./a.out 1122 22 1122 3 804a01c 0x804a01c delphi@delphi-vm:~/will$
Implicit type conversion is a type conversion actively performed by the compiler. It should be noted that the implicit type conversion from low type to high type is safe and does not cause truncation; but the implicit type conversion from high type to low type is not. Safe, will lead to incorrect results.
The point where implicit type conversion happens:
1. In arithmetic operations, the low type is converted to the high type;
2. In an assignment expression, the value of the expression is converted to the type of the variable on the left;
3. When the function is called, the actual parameter is converted to the type of the formal parameter;
4. The return value of the function, the return expression is converted to the return value type.
Important point - safe implicit type conversion:
char->(->short)->int->unsigned int->long->unsigned long->float->double
Example: Observe the following code and judge the output
intmain() { char c = 'a'; int i = c; unsigned int j = 0x11223344; //safe short s = j; //error truncation printf("%d\n", c); printf("%c\n", c); printf("%d\n", i); printf("%x\n", j); printf("%x\n", s); //truncate printf("sizeof(c + s) = %d\n", sizeof(c + s)); //Convert to int at the same time }
The result of compiling and running under linux Gcc is:
delphi@delphi-vm:~/will$ ./a.out 97 a 97 11223344 3344 sizeof(c + s) = 4
The type conversion of the standard C language compiler is relatively lenient, and diet type conversion may bring other errors.
Therefore, in actual programming, programmers should keep in mind the level of basic data types.