PiyushM
PiyushM

Reputation: 23

Why return statement works for void as return type in C?

NOTE: I am using windows 7 and gcc compiler on code blocks IDE.

I have found out that all forms of return statements can be used if the return type of function is void

for example:

void message() //If i skip this declaration still it works
main()
{
    message();
}
void message()
{
    return 5; //also return 5.0 and return a(some variable) also works
}

Since, void refers to 'nothing is returned' then how can we use return statements here. Does it mean that all programs return something whether it is void or other return type?

One more query I have regarding void as return type:

If I use this program

main()
{
    printf("%d",message());
}

void message()
{
}

It gives output as 1,

and doesn't give error

But I get an error if I use this:

void message(); //when I use the declaration

main()
{
    printf("%d",message());
}

void message()
{

}

Why does it happen?

Upvotes: 1

Views: 506

Answers (2)

The C11 standard draft n1570 says the following in the foreword:

Major changes in the second edition [that is, C99] included:

[...]

— return without expression not permitted in function that returns a value (and vice versa)


C89 standard then says the following:

Constraints

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

However, nothing is mentioned about prohibiting a return statement without an expression appearing in a function whose return type is not void.

Thus returning a value from void is not correct in C89 either.


Note that main() without return type is not allowed by C11 either. However, GCC is quite relaxed about many of these border cases, unless -pedantic-errors option is provided.

Upvotes: 3

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

I am not very sure about C89, but in C11, I can see in chapter §6.8.6.4

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

So, your code violates the standard.

Regarding the second part,

  • while missing declaration, due to the now-obsolete type-defaults-to-int property, it appeared to work, but it actually invoked undefined behavior, because, you're supplying a void type as int argument.

  • While having a forward declaration (with return type as void), due to mismatch of return type, error is prominent.

Upvotes: 5

Related Questions