12

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?

0

3 Answers 3

17

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.

The C23 standard, not yet published, will change this.

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

It's "valid" in the sense that the compiler needn't complain about it. But if the definition of f doesn't specify any parameters, then the behavior of f(1) is undefined. Without a prototype, it's entirely up to the programmer to get the number and type(s) of the arguments correct.
0

The void in this case just means "there are no parameters." I'm not sure whether your second case will compile, but either way I'd prefer the first case just to be as clear as possible. Of course, when calling f, you just use the empty parentheses:

int x = f(); 

2 Comments

Yes, the second case will compile. It's a function definition (which includes a function declaration) with no prototype. It's supported for compatibility with pre-ANSI C.
@KeithThompson, I'm glad to learn that from Keith Thompson and not from Ken Thompson. ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.