Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC : Return statement from a void function in C

Tags:

c

gcc

void

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.

like image 825
msc Avatar asked Aug 30 '25 16:08

msc


1 Answers

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.

like image 145
Sergey Kalinichenko Avatar answered Sep 03 '25 01:09

Sergey Kalinichenko