开发者

C function with no parameters behavior

Can somebody explain to me why the following code does compile without a warning or error?

I would expect the compiler to warn me that the function no_args doesn't expect any arguments.

But the code co开发者_StackOverflow社区mpiles and runs function no_args recursively.

static void has_args(int a, int b, int c) { 
    printf("has_args\n");
}

static void no_args() {
    printf("no_args\n");
    no_args(1, 2, 3);
}

void main() {
  no_args();
}


In C++, void no_args() declares a function that takes no parameters (and returns nothing).

In C, void no_args() declares a function that takes an unspecified (but not variable) number of parameters (and returns nothing). So all your calls are valid (according to the prototype) in C.

In C, use void no_args(void) to declare a function that truly takes no parameters (and returns nothing).


When you declare a function with an empty argument list, you invoke K&R (pre-prototype) semantics and nothing is assumed about the parameter list; this is so that pre-ANSI C code will still compile. If you want a prototyped function with an empty parameter list, use (void) instead of ().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜