Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function with no parameters behavior

Tags:

c

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 compiles 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(); } 
like image 983
John Retallack Avatar asked May 08 '11 19:05

John Retallack


People also ask

Can a function have no parameters C?

If a function takes no parameters, the parameters may be left empty. The compiler will not perform any type checking on function calls in this case. A better approach is to include the keyword "void" within the parentheses, to explicitly state that the function takes no parameters.

Can a function be without parameters?

The lesson brief states that “Functions can have zero, one or more parameters”.

What happens when you create a function without any parameters?

(1) The variable side is not given to the parameter, but directly accessed by the function which is possible in JavaScript. (2) The function does not return any value but prints the output to the browser console.

Do functions always need parameters?

Parameters are essential to functions, because otherwise you can't give the function-machine an input.


2 Answers

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).

like image 183
Chris Lutz Avatar answered Sep 24 '22 00:09

Chris Lutz


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 ().

like image 43
geekosaur Avatar answered Sep 22 '22 00:09

geekosaur