Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function prototype: void f(). Is it recommended?

Tags:

c

I'm learning C and I saw in a book that a function prototype has the form void f() and in the function declaration or in the calling function, the f function takes arguments.
Thus In the function declaration we have something like void f(long double y[], long double A) and in the calling function is f(y, A).
The function is doing operations on the array y i.e. when the function is called, some elements in the array y are changing. A is just a constant numerical value that doesn't change. I have two questions:

  1. If defining the function prototype at the top in the program as void f() a good practice? Or is it better to put it as void f(long double y[], long double A) as in the function declaration?

  2. The called function f is changing elements in the array y. Is void the right return type? The program is working fine as such with the void as described.
    Or should I change all my "voids" to "long double".
    I'm working with long double as I need as much precision as possible though on my machine both double and long double gives me 15 precision digits.

Thanks a lot

like image 868
yCalleecharan Avatar asked Apr 04 '10 09:04

yCalleecharan


2 Answers

Your question suffers from a terminological mix-up.

void f();

is not a function prototype in C. This is a function declaration that does not introduce a prototype. Meanwhile

void f(long double y[], long double A);

is also a function declaration, and this one is a prototype (i.e. it does introduce a prototype for f).

To answer your questions, yes, it is always a good practice to declare functions with prototypes (i.e. it is better to declare them with prototypes than without prototypes). Normally, you should declare prototypes for all your external functions (and void f() is not a prototype).

As for the return types, it is all a matter of your intent. I don't see how the fact that you are changing the elements of the array should make it better to return long double instead of void.

like image 149
AnT Avatar answered Sep 29 '22 23:09

AnT


If defining the function prototype at the top in the program as void f() a good practice? Or is it better to put it as void f(long double y[], long double A) as in the function declaration?

Definitely the latter -- the former doesn't give the compiler any type info for compile-time checks. void f() tells the compiler that f takes an unspecified argument list. I.e. anything goes.

The called function f is changing elements in the array y. Is void the right return type? The program is working fine as such with the void as described.

The return type has nothing to do with the parameter being modified. You can have a non-void return type if you want to indicate a success code though.

like image 39
Alex Budovski Avatar answered Sep 30 '22 01:09

Alex Budovski