问题描述
来自 C 编程语言第 2 版:
From The C Programming Language 2nd Edition:
由于函数调用的参数是表达式,因此在将参数传递给函数时也会发生类型转换.在没有函数原型的情况下,char 和 short 变成 int,float 变成 double.
通过阅读文本,我得到的印象是,除非您使用强制转换或函数原型明确指定参数类型,否则函数参数将始终以 int 或 double 形式传递.
By reading the text, I am getting an impression that unless you explicitly specify the argument type by either using cast or function prototype, function arguments will always be passed as either passed as int or double.
为了验证我的假设,我编译了以下代码:
In order to verify my assumption, I compiled the following code:
#include <stdio.h>
main()
{
unsigned char c = 'Z';
float number = 3.14f;
function_call(c, number);
}
void function_call(char c, float f)
{
}
编译后我收到以下警告:
After compilation I get the following warnings:
typeconversion.c:11:警告:function_call"的类型冲突
typeconversion.c:7:警告:function_call"的先前隐式声明在这里
typeconversion.c:7: warning: previous implicit declaration of ‘function_call’ was here
我的猜测是 c 和 number 在函数调用中都被转换为 int 和 double,然后又被转换回 char 和 float.真的是这样吗?
My guess is c and number were both converted to int and double on the function call, and were then converted back to char and float. Is this what actually happened?
推荐答案
演员表无关紧要,重要的是(可能是隐式的)原型.
Casts are irrelevant, it's the (possibly implicit) prototype that matters.
void foo(short s) {
// do something
}
int main(void) {
signed char c = 'a';
foo(c); // c is promoted to short by explicit prototype
bar(c); // c is promoted to int by implicit prototype
}
void bar(int i) {
// do something
}
当书中说函数调用的参数是一个表达式"时,这意味着相同的类型提升规则适用.如果您将函数参数视为对函数原型中指定的变量的隐式赋值,则可能更容易理解.例如在上面对 foo()
的调用中有一个隐式 short s = c
.
When the book says "an argument of a function call is an expression" it means that the same type promotion rules apply. It might be easier to understand if you think of a function argument as an implicit assignment to the variable specified in the function prototype. e.g. in the call to foo()
above there's an implicit short s = c
.
这就是演员表不重要的原因.考虑以下代码片段:
This is why casts don't matter. Consider the following code snippet:
signed char c = 'a';
int i = (short) c;
这里 c 的值首先提升为 short
(显式),然后提升为 int
(隐式).i
的值将始终是 int
.
Here the value of c is promoted first to short
(explicitly) then to int
(implicitly). The value of i
will always be an int
.
至于 char
和 short
变成 int
和 float
变成 double
那指隐式函数原型的默认类型.当编译器在看到原型或函数定义之前看到对函数的调用时,它会自动生成原型.它默认为 int
用于整数值和 double
用于浮点值.
As for char
and short
becoming int
and float
becoming double
that refers to the default types for implicit function prototypes. When the compiler sees a call to a function before it has seen either a prototype or the definition of the function it generates a prototype automatically. It defaults to int
for integer values and double
for floating-point values.
如果最终的函数声明与隐式原型不匹配,您将收到警告.
If the eventual function declaration doesn't match to implicit prototype, you'll get warnings.
这篇关于C:在函数调用中传递参数时的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!