gpt4 book ai didi

c - Visual C 接受错误数量的参数?

转载 作者:行者123 更新时间:2023-11-30 16:38:44 25 4
gpt4 key购买 nike

为什么在 Visual Studio 中编译:

void foo(int a) {}

int main() {
foo(1,2);
}

有警告

source_file.c(4) : warning C4020: 'foo' : too many actual parameters

但是为什么它不像 gcc/clang 那样是一个错误?

我知道 K&R 风格的函数定义,但这仅适用于需要可变数量参数的 foo()

引用允许这样做的标准将不胜感激。

最佳答案

这不仅仅是 MSVC。

如果您的函数定义位于调用站点下方并且没有原型(prototype),则 GCC 接受它。 C 始终允许调用未声明的函数。它从调用站点推断原型(prototype)。所以我认为该行为与该方面相关(尽管当我将函数移至 GCC 中的调用站点上方时,它会变为错误,这对于 C99 来说是有意义的)。尽管如此,这应该是未定义的行为(args 数量与参数数量不同)。

int main()
{
foo(1,2,3);
}

void foo(int a, int b)
{
}

f.c:6:6: warning: conflicting types for ‘foo’ [enabled by default]
void foo(int a, int b)
^
f.c:3:4: note: previous implicit declaration of ‘foo’ was here
foo(1,2,3);

我找到了这个

6.7.5.3p15:

[...] If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list [this is your situation], both shall agree in the number of parameters, and the type of each prototype parameter shall be compatible with the type that results from the application of the default argument promotions to the type of the corresponding identifier. [...]

.... but this paragraph is not part of a constraint. Violating a "shall" outside a constraint section is undefined behavior, not must-be-diagnosed behavior (4p2).

我引用自:http://compgroups.net/comp.lang.c/why-is-this-not-an-error-in-visual-c/732881

您的里程可能会有所不同。

简而言之,显然唯一的要求是编译器向您吠叫以获取吠叫的某些定义。在 VS 2013 中,它被视为错误。

就参数发生的情况而言,出于与可变参数列表在 C 中工作相同的原因,调用站点应该推送额外的参数,但被调用者不会意识到它(只是在这里猜测)。虽然它有效,但这并不意味着它是定义的行为。

关于c - Visual C 接受错误数量的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385857/

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