Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "void" in C

Tags:

c

I'm confused about why we need to pass void into C functions:

int f(void) { return 0; }

versus

int f() { return 0; }

What is the proper thing to do and why?

like image 941
Nate Avatar asked Sep 06 '11 19:09

Nate


People also ask

How is void used in C?

In C and C++A function with void result type ends either by reaching the end of the function or by executing a return statement with no returned value. The void type may also replace the argument list of a function prototype to indicate that the function takes no arguments.

Can we use void in C?

The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.

What does void * do in C?

It means "no value". You use void to indicate that a function doesn't return a value or that it has no parameters or both.


2 Answers

In C, int f() is an old-style declaration. It says that f expects a fixed but unspecified number and type(s) of arguments. For example, given int f() { return 0; }, the compiler won't complain about f(42), or f("hello, world") (though the behavior of such a call is undefined).

int f(void) explicitly says that f takes no arguments.

(C++ has different rules; Stroustrup wasn't as concerned about backward compatibility with old C code.)

like image 86
Keith Thompson Avatar answered Sep 28 '22 00:09

Keith Thompson


It's a vestige of C.

f(void) takes no arguments, so f(1) is invalid.

f() means that the parameters are unspecified, so f(1) is valid here.

like image 25
Foo Bah Avatar answered Sep 27 '22 22:09

Foo Bah