简体   繁体   English

为什么我们不能正确地将一个以上的参数传递给extern函数?

[英]Why cant we pass more than 1 argument correctly to an extern function?

I have the following code in my program: 我的程序中有以下代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int print_numbers_above(double x, float y, int z)
{
    printf("x=%lf, y=%f, z=%d\n", x, y, z);
}
int main()
{
    double x = 1.25;
    float y = 1.25;
    int z = 3;
    print_numbers_below(x, y, z);
    print_numbers_above(x, y, z);
    return 0;
}
int print_numbers_below(double x, float y, int z)
{
    printf("x=%lf, y=%f, z=%d\n", x, y, z);
}

Output: 输出:

x=1.25, y=0.000000, z=Garbage x = 1.25,y = 0.000000,z =垃圾

x=1.250000, y=1.250000, z=3 x = 1.250000,y = 1.250000,z = 3

Now, I know that the function print_numbers_below() should have been declared earlier (or should have been defined before main). 现在,我知道函数print_numbers_below()应该先声明(或者应该在main之前定义)。 But it doesn't throw an error. 但它不会引发错误。 It assumes it to be an extern function (and since it is returning int, there isn't any conflict of return types). 它假定它是一个extern函数(因为它返回int,所以没有任何返回类型的冲突)。 Now, I fail to understand why can't I pass more than 1 argument correctly? 现在,我无法理解为什么我不能正确传递超过1个参数?

(I'm using Visual Studio 2013) (我正在使用Visual Studio 2013)

A reasonable compiler would give you the following error: 合理的编译器会给你以下错误:

foo.c:12:5: warning: implicit declaration of function 'print_numbers_below' is invalid in C99 [-Wimplicit-function-declaration]
    print_numbers_below(x, y, z);
    ^
foo.c:16:5: error: conflicting types for 'print_numbers_below'
int print_numbers_below(double x, float y, int z)
    ^
foo.c:12:5: note: previous implicit declaration is here
    print_numbers_below(x, y, z);
    ^

When you call a function the compiler hasn't seen a prototype for, it applies the default argument promotions to all arguments. 当您调用函数时,编译器没有看到原型,它将默认参数提升应用于所有参数。 Chars and shorts are promoted to ints, and floats are promoted to doubles. Chars和短裤被提升为整体,并且花车被提升为双打。 This breaks when print_numbers_below actually wants a float. print_numbers_below实际上想要一个float时,这会中断。

If you haven't defined the function yet, always use a prototype. 如果尚未定义该功能,请始终使用原型。

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

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