简体   繁体   English

为什么可以将另一种类型的参数传递给函数?

[英]Why is it possible to pass an argument of another type to a function?

Consider the following piece of code:考虑以下代码:

void function (char arg)
{
    // function's content
}

int main(void)
{
    long double x = 1.23456;

    function(x);
}

I'm giving the function an argument it is not supposed to get.我给函数一个它不应该得到的参数。 Why does it not cause an error?为什么它不会导致错误?

It's converted implicitly.它是隐式转换的。

In the context of an assignment, argument passing, a return statement, and several others, an expression of any arithmetic type is implicitly converted to the type of the target if the target type is also arithmetic.在赋值、参数传递、 return语句和其他几个上下文中,如果目标类型也是算术类型,则任何算术类型的表达式都会隐式转换为目标类型。 In this case, the double argument is implicitly converted to char .在这种情况下, double参数被隐式转换为char (That particular conversion rarely makes sense, but it's valid as far as the language is concerned.) (这种特殊的转换很少有意义,但就语言而言它是有效的。)

Note that this implicit conversion is not done for variadic arguments (for example arguments to print after the format string), because the compiler doesn't know what the target type is.请注意,这种隐式转换不会对可变参数(例如在格式字符串后print参数)进行,因为编译器不知道目标类型是什么。 printf("%d\\n", 1.5) doesn't convert 1.5 from double to int ; printf("%d\\n", 1.5)不会将1.5double转换为int rather it has undefined behavior.相反,它具有未定义的行为。

There are also some rules for evaluating expressions with operators of different types.使用不同类型的运算符评估表达式也有一些规则。 I won't go into all the details here, but for example given:我不会在这里详细介绍,但举个例子:

int n = 42;
double x = 123.4;

if you write n + x the value of n is promoted (implicitly converted) from int to double before the addition is performed.如果你写n + x ,在执行加法之前n的值会从int提升(隐式转换)为double

在您的示例中, double类型被隐式转换为char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM