Cprogramming 简明教程
Type Conversion in C
C 编译器尝试数据类型转换,特别是在表达式中出现不同数据类型时。在某些时候,编译器会自行转换(隐式类型转换),以便数据类型彼此兼容。在其他情况下,C 编译器强制执行转换(显式类型转换),由类型转换运算符执行。
The C compiler attempts data type conversion, especially when dissimilar data types appear in an expression. There are certain times when the compiler does the conversion on its own (implicit type conversion) so that the data types are compatible with each other. On other occasions, the C compiler forcefully performs the conversion (explicit type conversion), which is carried out by the type cast operator.
Implicit Type Conversion in C
在 C 中,当编译器将一个值赋给变量的类型转换为另一个数据类型时,会自动进行隐式类型转换。这通常发生在将一个较小字节大小的类型赋值给一个“较大的”数据类型时。在这种隐式数据类型转换中,会保留数据完整性。
In C, implicit type conversion takes place automatically when the compiler converts the type of one value assigned to a variable to another data type. It typically happens when a type with smaller byte size is assigned to a "larger" data type. In such implicit data type conversion, the data integrity is preserved.
在执行隐式或自动类型转换时,C 编译器遵循类型提升规则。通常,遵循的原则是如下−
While performing implicit or automatic type conversions, the C compiler follows the rules of type promotions. Generally, the principle followed is as follows −
-
Byte and short values: They are promoted to int.
-
If one operand is a long: The entire expression is promoted to long.
-
If one operand is a float: The entire expression is promoted to float.
-
If any of the operands is double: The result is promoted to double.
Integer Promotion
整数提升是将类型“小于”int 或 unsigned int 的整数类型的值转换为 int 或 unsigned int 的过程。
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 an example of adding a character with an integer −
#include <stdio.h>
int main(){
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum: %d\n", sum);
return 0;
}
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
Value of sum: 116
此处,sum 的值为 116,因为编译器正在进行整数提升,并在执行实际加法操作前将 "c" 的值转换为 ASCII。
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
常见的算术转换隐式执行,以将其值转换为通用类型。编译器首先执行整数提升;如果操作数仍具有不同的类型,那么它们将转换为在以下层次结构中出现最高级别的类型:
Usual arithmetic conversions are implicitly performed to cast their values to a common type. 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 −
Example
以下是隐式类型转换的另一个示例:
Here is another example of implicit type conversion −
#include <stdio.h>
int main(){
char a = 'A';
float b = a + 5.5;
printf("%f", b);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
70.500000
当上述代码运行时,字符变量 "a"(其 int 等效值为 70)将转换为浮点数,因为加法表达式中的另一个操作数为浮点数。
When the above code runs, the char variable "a" (whose int equivalent value is 70) is promoted to float, as the other operand in the addition expression is a float.
Explicit Type Conversion in C
当您需要将字节大小较高的数据类型转换为字节大小较低的其他数据类型时,您需要明确告知编译器您的意图。这称为显式类型转换。
When you need to covert a data type with higher byte size to another data type having lower byte size, you need to specifically tell the compiler your intention. This is called explicit type conversion.
C 提供了一个类型转换运算符。您需要在要转换的操作数前用括号括住数据类型。
C provides a typecast operator. You need to put the data type in parenthesis before the operand to be converted.
type2 var2 = (type1) var1;
请注意,如果 type1 的长度小于 type2,则您不需要这种显式转换。仅当 type1 的长度大于 type2 时,才应该使用类型转换运算符。
Note that if type1 is smaller in length than type2, then you don’t need such explicit casting. It is only when type1 is greater in length than type2 that you should use the typecast operator.
当我们希望将较大数据类型变量降级到较小变量或将其转换为不相关类型(如浮点到整数)时,需要类型转换。
Typecasting is required when we want to demote a greater data type variable to a comparatively smaller one or convert it between unrelated types like float to int.
Example
考虑以下代码:-
Consider the following code −
#include <stdio.h>
int main(){
int x = 10, y = 4;
float z = x/y;
printf("%f", z);
return 0;
}
运行此代码,您将获得以下输出−
On running this code, you will get the following output −
2.000000
虽然我们希望结果为 10/4(即 2.5),但它显示为 2.000000。这是因为除法表达式中的两个操作数都是 int 类型。在 C 中,除法操作的结果始终为字节长度较大的数据类型。因此,我们必须将其中一个整数操作数类型转换到浮点,如下所示:
While we expect the result to be 10/4 (that is, 2.5), it shows 2.000000. It is because both the operands in the division expression are of int type. In C, the result of a division operation is always in the data type with larger byte length. Hence, we have to typecast one of the integer operands to float, as shown below −
Example
看看这个示例:
Take a look at this example −
#include <stdio.h>
int main(){
int x = 10, y = 4;
float z = (float)x/y;
printf("%f", z);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
2.500000
如果我们更改表达式,以便将除法本身转换为浮点数,结果将不同。
If we change the expression such that the division itself is cast to float, the result will be different.
Typecasting Functions in C
标准 C 库包含许多执行类型转换的函数。此处解释了一些函数:
The standard C library includes a number of functions that perform typecasting. Some of the functions are explained here −
The atoi() Function
atoi() 函数将字符串字符转换为整数。此函数在 stdlib.h 头文件中声明。
The atoi() function converts a string of characters to an integer value. The function is declared in the stdlib.h header file.
以下代码使用 atoi() 函数将字符串 "123" 转换为数字 123:
The following code uses the atoi() function to convert the string "123" to a number 123 −
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[] = "123";
int num = atoi(str);
printf("%d\n", num);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
123
The itoa() Function
您可以使用 itoa() 函数将整数转换为以 null 结尾的字符字符串。此函数在 stdlib.h 头文件中声明。
You can use the itoa() function to convert an integer to a null terminated string of characters. The function is declared in the stdlib.h header file.
以下代码使用 itoa() 函数将整数 123 转换为字符串 "123":
The following code uses itoa() function to convert an integer 123 to string "123" −
#include <stdio.h>
#include <stdlib.h>
int main(){
int num = 123;
char str[10];
itoa(num,str, 10);
printf("%s\n", str);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
123
使用类型转换的其他示例包括:
Other examples of using typecasting include the following −
The malloc() Function - malloc() 函数是一个动态内存分配函数。
The malloc() Function − The malloc() function is a dynamic memory allocation function.
Int *ptr = (int*)malloc(n * sizeof(int));
In function arguments and return values − 您可以将类型强制转换运算符应用于形式参数或用户定义函数的返回值。
In function arguments and return values − You can apply the typecast operator to formal arguments or to the return value of a user-defined function.
示例如下:
Here is an example −
#include <stdio.h>
#include <stdlib.h>
float divide(int, int);
int main(){
int x = 10, y = 4;
float z = divide(x, y);
printf("%f", z);
return 0;
}
float divide(int a, int b){
return (float)a/b;
}
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
2.500000
在 C 中使用隐式或显式类型转换有助于类型安全和提高代码可读性,但它也可能导致精度降低,并且其复杂的语法可能会令人困惑。
Employing implicit or explicit type conversion in C helps in type safety and improved code readability, but it may also lead to loss of precision and its complicated syntax may be confusing.