void bar()
means that bar
returns nothing. I'm curious to know, If void
returns nothing, then why doesn't the compiler(GCC) gives any warnings or errors, when compiling following program?
#include <stdio.h>
void foo (void)
{
printf("In foo() function\n");
}
void bar (void)
{
printf("In bar() function\n");
return foo(); // Note this return statement.
}
int main (void)
{
bar();
return 0;
}
I have compiled using gcc -Wall myprog.c
, and it's working fine.
This construct has been disallowed in C99:
return
without expression not permitted in function that returns a value (and vice versa)
Compiling with proper version of standard compliance turned on produces an appropriate error:
prog.c:11:16: error: ISO C forbids ‘return’ with expression, in function returning void [-Werror=pedantic]
return foo(); // Note this return statement. ^~~~~
As for the reason why this worked with older versions of C, the original K&R lacked void
keyword, so programmers who wanted to make it explicit that the function does not return anything were using preprocessor with #define VOID int
or something similar. Of course, this "poor man's void
" allowed returning an int
value, so the code from your post would perfectly compile. My guess is that the authors of earlier versions of the standard were reluctant to plug this hole, because it would be a breaking change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With