-2

I tried to write a void function with a return type and for some reason that works fine. Here is the some code I tried to compile:

void a(){
  return b();
}
void b()
{
   printf("%s","void:)");
}

And the next code also works correctly:

 int main()
 {
  a();
  return 0;
 }

 void a(){
  return 5;
 }

Which of the above is correct according to the standard?

Second, why does it compile?

unwind
  • 391,730
  • 64
  • 469
  • 606
Malic Of Sdom
  • 431
  • 1
  • 3
  • 10

2 Answers2

3

Which of the above is correct according to the standard?

Neither is correct according to C and C++ standard. C standard says that:

6.8.6.4 The return statement:

A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

Also read this answer for more detailed explanation.

Second, why does it compile?

Compilation doesn't guarantee that your code can't produce errors. It can. Better to compile your code with maximum warning flags. I compiled the second code with following options and got the following warnings:

In function 'main':
    [Warning] implicit declaration of function 'a' [-Wimplicit-function-declaration]
At top level:
    [Warning] conflicting types for 'a' [enabled by default]
    [Note] previous implicit declaration of 'a' was here
In function 'a':
    [Warning] 'return' with a value, in function returning void [enabled by default]  

Although code compiled but there are some errors and violation of C standard.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
1

Both programs are invalid. You failed to provide a function definition or declaration of b() in the first program before calling it in a(), and you failed to provide a function definition of a() before calling it in main() in the second program.

Your compiler is providing a "default" prototype for an undeclared function:

int func();

which is a function taking any arguments and returning int. This is probably not what you want. Your compiler should have issued a warning saying that it was supplying a default function declaration.

If you forward-declare the functions correctly (void b(); and void a();), the compiler will correctly reject both programs.

nneonneo
  • 171,345
  • 36
  • 312
  • 383