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

查看:298
本文介绍了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:

双sqrt(双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:

为什么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;

()的pdf"rel =" noreferrer> 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天全站免登陆