c中函数调用期间的类型转换 [英] Type conversion during function call in c

查看:16
本文介绍了c中函数调用期间的类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 K & 的《C 编程语言》一书.R 学习 C.它说

I am going through the book The C programming Language by K & R to learn c. It says that

由于函数调用的参数是表达式,因此类型转换当参数传递给函数时也会发生.在里面没有函数原型,char和short变成int,float变成双倍.

Since an argument of a function call is an expression, type conversion also takes place when arguments are passed to functions. In the absence of a function prototype, char and short become int, and float becomes double.

过去几天我一直在努力理解这条线.我认为这是很重要的一点.无论我做出什么假设,它都不会实现.谁能帮我理解清楚?

I am struggling over this line for the past few days to understand. I think it is an important point. Whatever assumptions that I am making, its not coming true. Can anybody help me to understand it clearly?

推荐答案

在 ANSI C 之前的版本中,函数没有原型是很常见的.在这种情况下,只发生了默认类型的促销.

In pre-ANSI C it was common to have functions with no prototype. In this case only the default type promotions took place.

当有原型时,每个参数表达式都被转换为函数期望的类型,就像有一个强制转换:

When there is a prototype, each parameter expression is converted to the type expected by the function, as if there were a cast:

// Declaration
void callMe(char x, int y);
...
// Call
callMe(50, 'x');

上面的调用相当于调用

callMe((char)50, (int)'x');

这很重要,因为调用者和被调用者之间就传递参数达成了隐含的协议:传递参数的方式以及参数的内存占用取决于类型.如果调用者没有以正确的格式在内存中放置参数,被调用者将无法正确使用这些参数.这就是为什么两者必须以某种方式就每个参数的类型达成一致.该标准说协议"以函数原型的形式出现.如果原型缺失,标准提供默认协议",即charshort变成intfloat 变为 double.

This is important because of an implicit agreement between the caller and the callee on passing parameters: the way a parameter is passed, as well as the memory footprint of the parameter, depends on the type. If the caller does not place parameters in memory in the right format, the callee would not be able to use the parameters correctly. That's why the two must agree on the type of each parameter in some way. The standard says that the "agreement" comes in the shape of a function prototype. If the prototype is missing, the standard supplies the "default agreement", i.e. char and short become int, and float becomes double.

这篇关于c中函数调用期间的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆