void as function argument

Mar 24, 2014 at 5:36pm
Hi,
I was reading about void as function argument, but I did not fully understand it's meaning in C.

In C++
void foo(void) {}
and
void foo() {}

are the same. It means no arguments for foo function. But in C it's different. First function means the same as in C++, but second means
In C, an empty parameter list means that the number and type of the function arguments are unknown.

But if it is unknown you can't use this arguments if user specifies same. Because here are no variables to store them. So doesn't result are the some? You do not get any arguments. O do I can get this arguments from some hidden variable?

For example.
1
2
3
4
5
6
void foo()
{
    printf("%d", var);
}

foo(5);


It is very unclear for me.

P.S. do this apply to main function too?
int main(void)
int main()
or can I use arguments given to int main() like given to int main(int argc, char* argv[])
Last edited on Mar 24, 2014 at 5:42pm
Mar 24, 2014 at 6:02pm
Shinigami wrote:

But if it is unknown you can't use this arguments if user specifies same. Because here are no variables to store them.

It's as simple as that.
Mar 24, 2014 at 6:18pm
So, this specifications in C makes bugs which can't be caught by compiler?
Mar 24, 2014 at 6:28pm
Bug? Feature? That might be open to dispute.
Mar 24, 2014 at 6:37pm
In C, it is legal for your function prototypes to not specify the arguments to the function. So it is legal to have in your header file:

1
2
3
/* My function prototypes */
void Function1();
int Function2();


And in the function definitions:

1
2
3
4
5
6
7
8
9
10
11
12
/* My function definitions */
void Function1(int a)
{
  printf("The value of a is %d", a);
}

int Function2(char *message)
{
  printf("%s", message);

  return 42;
}


Obviously, for the function definitions, you need to define what the arguments are. But you don't need them in the prototypes. Of course, if you do this, then the compiler can't check whether you're passing the correct arguments, which could lead to bugs. So it's a lazy and, frankly, a stupid thing to do.

(Note that I'm not knowledgeable about modern C standards, so this may have changed in modern standards.)

EDIT: There's more discussion under this StackOverflow topic, if you're interested:

http://stackoverflow.com/questions/13950642/why-does-a-function-with-no-parameters-compared-to-the-actual-function-definiti
Last edited on Mar 24, 2014 at 6:38pm
Topic archived. No new replies allowed.