简体   繁体   English

函数期望在C中返回值

[英]Function expects to return value in C

I'm a newbie at C, I am working on someone else's code and I am trying to get rid of a warning that looks like this: 我是C的新手,正在研究其他人的代码,并且试图摆脱看起来像这样的警告:

warning: function expects to return value: myfunc

myfunc is declared like this, (I believe it defaults to int) myfunc这样声明,(我相信它默认为int)

myfunc(int id, int age) {

   ...
   return;

}

So I try to put void behind myfunc so that it looks like this 因此,我尝试在myfunc后面放置空白,使其看起来像这样

void myfunc(int num, int age) {

I get an error: 我收到一个错误:

identifier redeclared: myfunc 重新声明的标识符:myfunc

  current : function() returning void previous: function() returning int : "students.c", line 233 

But when I go to line 233 of students.c, this is just the first place that I actually call the function. 但是,当我转到students.c的第233行时,这只是我实际调用该函数的第一个地方。 Why is this happening? 为什么会这样呢?

I know I could change return to return 0; 我知道我可以将return更改为return 0; and then define myfunc as int. 然后将myfunc定义为int。 But when this function is called, it's not assigned to anything, it's just executed like myfunc(current_id, age); 但是当调用此函数时,它没有分配任何内容,只是像myfunc(current_id, age);一样执行myfunc(current_id, age); (not int i = myfunc(... for example). (不是int i = myfunc(...例如int i = myfunc(... )。

In a situation like this, would it best not to use void? 在这种情况下,最好不要使用void吗? Is it ok to use return; 可以使用return;return; in a void function? void函数中?

Thanks! 谢谢!

The function myfunc() is declared with no return type (somewhere): 函数myfunc()声明为不带返回类型(某处):

myfunc(int id, int age);

or there is no declaration at all, so it defaults to an int return type. 或根本没有声明,因此它默认为int返回类型。 When you specify void at the definition: 在定义中指定void时:

void myfunc(int id, int age)
{
}

it does not match the declaration. 它与声明不匹配。 Change, or add, the declaration: 更改或添加声明:

void myfunc(int id, int age);

You don't need to explicitly write return; 您无需显式编写return; in a function with a void return type, but you can if you wish. 在具有void返回类型的函数中,但是如果您愿意,也可以。

You did the right thing by adding void to that implementation of myfunc . 您通过在myfunc实现中添加void myfunc正确的事情。 However, it looks like the original programmer was sloppy and didn't declare a function prototype for myfunc before using it in students.c . 但是,看起来原始的程序员很草率,并且在students.c使用myfunc之前没有声明函数原型。 Add that prototype somewhere before line 233 and you should be good to go! 在第233行之前的位置添加该原型,您应该一切顺利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM