Home > Net >  "‘return’ with a value, in function returning void" when returning a struct
"‘return’ with a value, in function returning void" when returning a struct

Time:11-05

I am getting compilation error:

warning: ‘return’ with a value, in function returning void

Here is my code:

#include <stdio.h>

typedef struct
{
  int a;
  char b;
}
values;

values keyword;

struct values get_keyword(void)
{
  return keyword;
}

int main()
{
   keyword.a = 10; 
}

CodePudding user response:

struct values is not a type. values is though, since you typedefined it:

Corrected:

values get_keyword(void) {
    return keyword;
}

A more complete output from when compiling your program would include this first error:

<source>:10:15: error: return type is an incomplete type
   10 | struct values get_keyword(void) {
      |               ^~~~~~~~~~~
<source>: In function 'get_keyword':

So, now get_keyword becomes void which triggers the secondary error you showed in the question:

<source>:11:12: warning: 'return' with a value, in function returning void
   11 |     return keyword;
      |            ^~~~~~~
<source>:10:15: note: declared here
   10 | struct values get_keyword(void) {
      |               ^~~~~~~~~~~
ASM generation compiler returned: 1

Previous errors often explains later errors, which was the case here.

CodePudding user response:

Your struct has no tag, only typedefed alias name values.

typedef struct
{
    int a;
    char b;
}values;

values keyword;

values get_keyword(void)
{
   return keyword;
}

If you want to use it without using the alias (but still to use typedef) you need to add the tag:

typedef struct values
{
    int a;
    char b;
}values;

values keyword;

struct values get_keyword(void)
{
    return keyword;
}
  • Related