sqrt() - 为什么我可以提供 int 参数而不是 double 并且输出也是正确的? [英] sqrt() - Why am I allowed to provide an argument of int and not only double and the output is also right?

查看:25
本文介绍了sqrt() - 为什么我可以提供 int 参数而不是 double 并且输出也是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么编译器让这个通过并给出正确的输出,尽管 sqrt() 从它的原型通常应该只得到一个 double 值作为参数:

I wondering why the compiler let this pass and is giving the right output, although sqrt() from its prototype normally should only get an double value as argument:

在 C99 中,原型的声明是:

In C99 the declaration of the prototype is:

double sqrt(double x);

double sqrt (double x);

#include <stdio.h>
#include <math.h>

int main (void)
{  
   int i = 9;

   printf("\t Number \t\t Square Root of Number\n\n");

   printf("\t %d \t\t\t %f \n",i, sqrt(i)); 

}

输出:

 Number      Square Root of Number

 9           3.000000 

如果我给 sqrt() 函数一个 int 作为参数,为什么编译器至少不抛出警告并且给定的输出是正确的?

Why does the compiler not throw a warning at least and the given output is right, if I´m giving the sqrt() function an int as argument?

这是进入未定义行为吗?

Is this crossing into Undefined Behavior?

我正在使用 gcc.

这个问题已经针对 C++ 提出了两次,但没有针对 C,所以我的问题是针对 C 的.无论如何,我提供了 C++ 问题的链接:

The Question was already asked twice for C++, but not for C, so my question is up for C. I provide the links to the questions for C++ anyway:

如果不是为 int 定义的,sqrt() 为什么可以在 int 变量上正常工作?

为什么 sqrt() 使用 int 参数?

推荐答案

这不是未定义的行为.

该函数被定义为接受 double 类型的参数.因为参数的类型是已知的,所以您可以传递一个 int,因为它可能会被隐式转换为 double.这和你做的一样:

The function is defined to accept an argument of type double. Because the type of the argument is known, you can pass an int because it may be implicitly converted to a double. It's the same as if you did:

int i = 4;
double d = i;

函数参数的转换规则在 C 标准关于函数调用操作符():

The rules for conversion of function arguments are spelled out in section 6.5.2.2p7 of the C standard regarding the function call operator ():

如果表示被调用函数的表达式的类型为确实包含一个原型,参数被隐式转换,如如果通过赋值,给对应参数的类型,取每个参数的类型是其非限定版本声明的类型. 函数原型中的省略号声明符导致参数类型转换在最后一个之后停止声明的参数.默认参数提升在尾随参数

If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments

相反,如果在格式字符串需要 double 时将 int 传递给 printf,即:

In contrast, if you passed an int to printf when the format string expects a double, i.e.:

printf("%f\n", 4);

然后你有未定义的行为.这是因为在编译时不知道参数的类型,因此无法进行隐式转换.

Then you have undefined behavior. This is because the types of the arguments are not known at compile time so the implicit conversion can't happen.

这篇关于sqrt() - 为什么我可以提供 int 参数而不是 double 并且输出也是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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