问题描述
从C程序设计语言第2版:
From The C Programming Language 2nd Edition:
由于函数调用的参数是一个前pression,当参数传递给函数的类型转换也发生。在缺少函数原型,焦炭和短成为int和float变成双。
通过阅读文本,我得到一个IM pression,除非你明确地通过铸造或函数原型或者指定的参数类型,函数参数将始终是无论是作为int或双传递过去。
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.
为了验证我的假设,我整理了以下code:
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'previous隐式声明在这里
typeconversion.c:7: warning: previous implicit declaration of ‘function_call’ was here
我的猜测是C和数量均转换成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
}
在书中说:一个函数调用的参数是一个前pression这意味着同一类型的促销规则。这可能是更容易理解,如果你认为一个函数的参数作为隐式分配函数原型中指定的变量。例如在调用富()
上方有一个隐含的短S =ç
。
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
.
这是为什么石膏并不重要。请看下面的code片断:
This is why casts don't matter. Consider the following code snippet:
signed char c = 'a';
int i = (short) c;
下面c的值是第一个晋升为短
(明确的)然后 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
.
至于字符
和短
成为 INT
和浮动
成为双击
引用的默认类型隐函数原型。当编译器看到一个呼叫到一个函数之前它已经看到任一个原型或它自动生成一个原型函数的定义。它默认为 INT
的整数值和双击
浮点值。
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:传递参数时,类型转换的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!