Declare a void function in C?

送分小仙女□ 提交于 2019-12-03 09:02:49
Nemanja Boric

If you don't have forward declaration of your function before the place of usage, compiler will create implicit declaration for you - with the signature int input() - it will take the name of the function you called, it will assume that the function is returning int and it can accept any arguments (as Bartek noted in the comment).

For this function, implicit declaration matches the real declaration, so you don't have problems. However, you should always be careful about this, and you should always prefer forward declarations instead of implicit ones (no matter if they are same or not). So, instead of just having forward declaration of the void prime() function (assuming that you will use it somewhere), you should also have forward declaration of int input().

To see how can you pass any number of the arguments, consider this:

#include <stdio.h>

// takes any number of the arguments
int foo();

// takes no arguments
int bar(void)
{
      printf("Hello from bar()!\n");
      return 0;
}

int main()
{
      // both works

      // However, this will print junk as you're not pushing
      // any arguments on the stack - but the compiler will assume you are
      foo();

      // this will print 1, 2, 3
      foo(1, 2, 3);

      // works
      bar();

      // doesn't work
      // bar(1, 2, 3);

      return 0;
}

// definition
int foo(int i, int j, int k)
{
     printf("%d %d %d\n", i, j, k);
     return 0;
}

So, inside the definition of the function you're describing function arguments. However, declaration of the function is telling the compiler not to do any checks on the parameters.

Not declaring a prototype and relying on default argument/return type promotion is dangerous and was a part of old C. In C99 and onward it is illegal to call a function without first providing a declaration or definition of the function.

my question is, is it necessary to declare a void function with not arguments?

Yes. For this you have to put void in the function parenthesis.

void foo(void);  

Declaring a function like

void foo();  

means that it can take any number of arguments.

If prime is not used, then omit the declaration.

The code won't compile as C++ because the compiler would complain that function input is used but not declared. A C compiler might issue a warning, but C is more relaxed and does an implicit declaration of input as int input() which means that you can pass any value to input and input returns an int.

It is good style to always provide a function declaration before using the function. Only if you do this the compiler can see if you are passing to few, to many or wrongly typed arguments and how to correctly handle the return value (which might be short or char instead of int).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!