gpt4 book ai didi

在 c 中进行转换会导致任何编译错误吗?

转载 作者:行者123 更新时间:2023-11-30 18:27:57 24 4
gpt4 key购买 nike

我知道在java中我不能从一个应该在不进行转换的情况下返回int值的函数返回double,但是现在当我学习c时我发现我可以编译类似的东西(只有警告,没有错误):

int calc(double d, char c) {
return d * c / 3;
}

所以我的问题是,c 编译器总是会在需要时为我进行自动转换?或者这是由于字符或其他原因而导致的特定工作?

最佳答案

C 有一个隐式转换的概念,即定义在什么条件下以及如何将值隐式转换为不同类型的规则,而无需显式转换它们(例如,参见 cppreference.com )。所以 C 并不是“自动类型转换”一切,而是仅在某些条件下“自动类型转换”。

您的返回类型是int,而表达式d * c/3的结果是double。因此以下(隐式)转换适用:

Real floating-integer conversions

A finite value of any real floating type can be implicitly converted to any integer type. Except where covered by boolean conversion above, the rules are: The fractional part is discarded (truncated towards zero). If the resulting value can be represented by the target type, that value is used otherwise, the behavior is undefined

关于在 c 中进行转换会导致任何编译错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51118655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com