4

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.

4
  • Because even though it returns nothing you can still use return to interrupt the function. Commented Mar 22, 2017 at 5:54
  • @Havenard: Your comment does not make sense. Commented Mar 22, 2017 at 6:18
  • Which version of gcc do you use? Versions before 5 default to non-standard C90 which is outdated since 18 years. Use a more recent version or speficy standard C, i.e. C11 - at least C99. Commented Mar 22, 2017 at 6:20
  • 1
    The code is accepted as an extension (it is valid in C++), and no warning is printed in non-pedantic mode because it doesn't seem likely to cause any issue: you are using consistent return types for foo and bar. Commented Mar 22, 2017 at 8:24

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.